Not sending XML command with fixed header via TCP/IP using Java - java

I'm new to Java (basically had to learn it on the fly for this project), but I'm trying to send an XML command to a server to get some data from it. To do this, I've written a Java program and I'm running it from the command line.
Here's my Java code for a reference. I got most of this from a client/server TCP tutorial and adjusted the IP, port, and outgoing message accordingly. Again, I'm very new to this, so any help is appreciated.
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.BufferedInputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class GDC {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
System.out.println("Attempting connection to GE Reuter Stokes");
// establish the socket connection to the server
// using the local IP address, if server is running on some other IP, use that
Socket socket = new Socket(<SERVER_IP>, <SERVER_PORT>);
System.out.println("Socket Connected");
// write to socket using OutputStream
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
// Initializing request content
byte[] request = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><command version=\"2.2\" cmd=\"HEARTBEAT\"/>".getBytes(StandardCharsets.UTF_8);
// DataOutputStream.writeInt() writes in big endian and
// DataInputStream.readInt() reads in big endian.
// using a ByteBuffer to handle little endian instead.
byte[] header = new byte[5];
ByteBuffer buf = ByteBuffer.wrap(header, 1, 4);
buf.order(ByteOrder.LITTLE_ENDIAN);
// Initializing request header
header[0] = (byte) 0x060E2B34;
header[1] = (byte) 0x02050101;
header[2] = (byte) 0x0F150111;
header[3] = (byte) 0x00000000;
buf.putInt(request.length);
System.out.println("Sending request to Socket Server");
// Sending request
dos.write(header);
dos.write(request);
dos.flush();
System.out.println("Request was sent. Awaiting response.");
// read from socket using InputStream
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
// Read response header
dis.readFully(header);
buf.flip();
// Read response content
byte[] response = new byte[buf.getInt()];
dis.readFully(response);
// convert the content into a string
String message = new String(response, StandardCharsets.UTF_8);
System.out.println("Message: " + message);
// close your resources
dis.close();
dos.close();
socket.close();
Thread.sleep(100);
}
}
I want to send XML request using the following instruction :
I got an error like follow:
Attempting connection to GE Reuter Stokes
Socket Connected
Sending request to Socket Server
Request was sent. Awaiting response.
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at java.io.DataInputStream.readFully(DataInputStream.java:195)
at java.io.DataInputStream.readFully(DataInputStream.java:169)
at GDC.main(GDC.java:54)

Related

how to connect Restful API and socket server in java

I created restful API(with maven) which connect to MySQL. I want to connect with the Java socket server I created earlier. But I couldn't figure out how to do this. I tried to connect with HttpURLConnection over Server.java but it didn't connect yet. Is it a good way to connect? Or should i try different way for this? And also I created new maven project and putted Server.Java and Client.Java in it. But it is a just attempt. I am not sure is it necessary or not.
Server.JAVA
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Server {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
// System.out.println("Client accepted");
// HttpURLConnection attempt
URL url = new URL("http://localhost:8080/update/3");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setRequestProperty("Content-Type", "application/json");
http.setDoOutput(true);
OutputStream stream = http.getOutputStream();
String data = "{\n \"firstName\":\"Can\",\n \"lastName\":\"Doe\",\n \"occupation\":\"xxx\"\n}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
stream.write(out);
System.out.println(http.getResponseCode() + http.getResponseMessage());
http.disconnect();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Stop" is sent
while (!line.equals("Stop"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server( 5000);
}
}

multithreaded client and server in distributed system (Java)

Am new to Socket programming am trying to establish a communication between a Server and a client but i don't know how to do that am a bit confused on how to go about it. I have written the program below but it is given error and i can't get my head round why.
package server;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Server {
public static void main(String[] args) {
// TODO code application logic here
try {
DatagramSocket socket = new DatagramSocket(7000);
socket.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
String message = new String (buffer);
System.out.println(message);
String Reply ="Am here";
DatagramPacket data = new DatagramPacket(Reply.getBytes(), Reply.getBytes().length, packet.getAddress(), packet.getPort());
socket.send(data);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
Client
package client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) {
// TODO code application logic here
try{
String message = "Hello Server";
String host = "localhost";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 7000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
DatagramSocket sockets = new DatagramSocket(7000);
sockets.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packets = new DatagramPacket(buffer,buffer.length);
sockets.receive(packets);
String messages = new String (buffer);
System.out.println(messages);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
How can i get them communicated. I have heard about Multi-threading but can't get my head round how it works.
I get the following error.
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagramSocketImpl.java:84)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:93)
at java.net.DatagramSocket.bind(DatagramSocket.java:392)
at java.net.DatagramSocket.<init>(DatagramSocket.java:242)
at java.net.DatagramSocket.<init>(DatagramSocket.java:299)
at java.net.DatagramSocket.<init>(DatagramSocket.java:271)
at client.Client.main(Client.java:32)
If you wanting to send/receive from a client to a server using a socket then use ServerSocket on the serverside.
Then use accept - This listens for a connection to be made to this socket and accepts it.
The Socket object returned by Accept has Input and Output Stream which can be be read and written to.
The client will just use a Socket Object
See http://cs.lmu.edu/~ray/notes/javanetexamples/ for an example
If for some reason you insist on using DatagramSocket, then see this example https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
The error occurs because the port you are trying to bind your socket to is already in use. Port 7000 is used both by the client and server:
DatagramSocket sockets = new DatagramSocket(7000);

Java-based 2 way chat application not working

For its partner app I switched the Client and Server code and the ports. Ran both these codes in two separate terminals. They were able to connect with each other but I was not able send message from one terminal to the other.
import java.net.*;
import java.io.*;
import java.util.Scanner;
class ChatHead1
{
public static void main()throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Client
Socket sock = new Socket("127.0.0.1", 2000);
OutputStream ostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);
System.out.print("\nYou:");
String message1 = br.readLine(); //Inputting Message For Sending
dos.writeBytes(message1);
//Server
ServerSocket sersock = new ServerSocket(5000);
System.out.print("\nThem: ");
Socket sockServ = sersock.accept();
InputStream istream = sockServ.getInputStream();
DataInputStream dstream = new DataInputStream(istream);
String message2 = dstream.readLine();
System.out.println(message2); //Printing Received Message
//Client Close
dos.close();
ostream.close();
sock.close();
//Server Close
dstream .close();
istream.close();
sockServ.close();
sersock.close();
}
}
I would suggest that you should only use one Server/Client, because its a two way connection.
I dont really see why you are using a Client and a Server.
Try dos.flush(); after dos.writeBytes(message1);

why doesn't the server receive the object sent from the client?

How do I handle the ObjectOutputStream and ObjectInputStream so that the Server instance correctly logs the received Object. Currently, it never gets that far. Each time the client runs, the server "waits for data", but never seems to actually receive it.
server:
package net.bounceme.dur.driver;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
private static final Logger log = Logger.getLogger(Server.class.getName());
private final RecordQueue recordsQueue = new RecordQueue();
public static void main(String[] args) {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
while (true) {
try {
new Server().inOut(portNumber);
} catch (java.net.SocketException se) {
Logger.getLogger(Server.class.getName()).log(Level.FINE, "spammy", se);
} catch (IOException ioe) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ioe);
} catch (ClassNotFoundException cnf) {
Logger.getLogger(Server.class.getName()).log(Level.INFO, null, cnf);
}
}
}
public void inOut(int portNumber) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket socket = serverSocket.accept();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
log.info("...connected...waiting for data...");
MyRecord recordFromClient = (MyRecord) objectInputStream.readObject();
objectOutputStream.writeObject(recordFromClient);
objectOutputStream.flush();
objectInputStream.close();
objectOutputStream.close();
log.info(recordFromClient.toString());//never logs
System.out.println("never gets here");
}
}
Each time the client runs, the server waits for data, but, at least according to the output below, never receives it.
thufir#dur:~$
thufir#dur:~$ java -jar NetBeansProjects/Server/dist/Server.jar
Jun 29, 2014 9:28:45 PM net.bounceme.dur.driver.Server inOut
INFO: ...connected...waiting for data...
Jun 29, 2014 9:28:46 PM net.bounceme.dur.driver.Server inOut
INFO: ...connected...waiting for data...
client code:
package net.bounceme.dur.driver;
import java.net.*;
import java.io.*;
import java.util.Properties;
import java.util.logging.Logger;
public class Client {
private static final Logger log = Logger.getLogger(Client.class.getName());
public void put(String server, int portNumber, Socket socket, ObjectOutputStream objectOutputStream) throws IOException, ClassNotFoundException {
socket = new Socket(server, portNumber);
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
MyRecord record = new MyRecord(1, "foo");
objectOutputStream.writeObject(record);
objectOutputStream.flush();
objectOutputStream.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
String server = (props.getProperty("server"));
Socket socket = null;
ObjectOutputStream objectOutputStream = null;
ObjectInputStream objectInputStream = null;
new Client().put(server, portNumber, socket, objectOutputStream);
}
}
Client and Server must agree with each other not only about how they send data but also when to close a socket. A unilateral close of a socket will close the connection and thwart the reception even of data that has already been sent. And I think that's what's happening here.
Client code:
objectOutputStream.writeObject(record);
objectOutputStream.flush();
objectOutputStream.close();
This is executed without interruption and so the socket is closed as soon as the last byte has been sent on the wire. Thus, the server's reply cannot be sent.
Server code:
MyRecord recordFromClient = (MyRecord) objectInputStream.readObject();
objectOutputStream.writeObject(recordFromClient);
Clearly, reception happens a little later than sending, and so the server blocks.
Keep the socket open from both sides until the client has received; then he may close the socket. The server should see an end-of-file when trying to read again, and can close accordingly. (More elaborate handshaking is possible, of course.)
Later
To corroberate, simply add a Thread.sleep(2000); between Client's flush and close - and the Server will indeed "get here".

Continuous data sending and receiving [duplicate]

This question already has answers here:
Java Socket why server can not reply client
(4 answers)
Closed 3 years ago.
I'm very new to socket programming. I have a requirement on continuously sending and receiving data between client and server. Below the process flow needs to be done.
Client sends "Client Hello" message to Server.
Server sends "Server hello" message to Client.
Client Sends "What is your server id?" message to Server
Server sends "My ID is #1" message to Client.
Client sends "Thank you" message to Server.
Server send "You are welcome" message to client
I tried to do this using Java sockets API. But i can't send multiple messages using a one socket. only 1 and 2 messages were able to transmit. Can someone tell me a way to achieve this requirement? Highly appreciate if someone give me an advise on this.
This is the server side program
package socketserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer{
public static void main(String args[]){
final int SocketServerPORT = 4000;
try{
ServerSocket serverSocket = new ServerSocket(SocketServerPORT);
System.out.println("Server is started with port"+ serverSocket.getLocalPort());
System.out.println("Waiting for connection...");
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Receiving Client Hello
System.out.println(input.readLine());
PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//Sending Server Hello
output.write("Server Hello");
output.flush();
//Recieving Client message asking regarding Server ID
System.out.println(input.readLine());
//Sending Server ID to client
output.write("MY Server ID is #1");
output.flush();
//Recieving Client Thank you message
System.out.println(input.readLine());
//Sending Welcome message to Client
output.write("You are welcome.");
output.flush();
output.close();
input.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below is the Client Side program
package socketclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) {
final int socketServerPORT = 4000;
final String host="127.0.0.1";
try {
Socket clientSocket=new Socket(host,socketServerPORT);
PrintWriter output = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
//Sending Client Hello
output.println("Client Hello");
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Receiving Server Hello
System.out.println(input.readLine());
//Asking for Server ID
output.println("What is your Server ID");
output.flush();
//Receving Server ID
System.out.println(input.readLine());
//Sending Thank you message to Server
output.println("Thank you.");
output.flush();
//Receving Welcome message from Server
System.out.println(input.readLine());
output.close();
input.close();
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You are reading lines but you aren't writing lines. The readLine() method blocks until a line terminator or end of stream occurs. You need to either append \n to each message or use println() instead of write().

Categories

Resources