Java sockets java.io.EOFException - java

Getting Exception in thread "main" java.io.EOFException
at the last line of code, why? and how to fix... Thanks.
String ip = "XXX.XX.XX.XXX";
int port = XXXXX;
Socket socket = null;
System.out.println("in function");
socket = new Socket(ip, port);
System.out.println("in function - After Socket");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("in function - After ObjectOutputStream");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

The peer has already closed the socket. Possibly you sent it something it didn't understand. Unless it is a Java program that also uses object inout and output streams, it definitely won't understand.

Related

Java socket port number changes on its own

Client
try {
Socket sock = new Socket("localhost", Integer.parseInt(args[0]));
System.out.println(sock.getLocalAddress());
System.out.println(sock.getLocalPort());
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeInt(55);
ois.readInt();
} catch (Exception e) {e.printStackTrace();}
Server
try {
ServerSocket ss = new ServerSocket(1234);
Socket sock = ss.accept();
System.out.println(sock.getLocalAddress());
System.out.println(sock.getLocalPort());
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
System.out.println(ois.readInt());
oos.close();
} catch (Exception e) {e.printStackTrace();}
I run the server and then the client, in that order.
I pass 1234 as a command-line argument to the client. In other words, I execute threads this way
java server
java client 1234
Doing that prints these to the console
// server
/127.0.0.1
1224
// client
/127.0.0.1
50261
Neither threads move on from this point.
What's going on here?
Java socket port number changes on its own
No it doesn't. You're looking at two different sockets and two different ports. A connection consists of two endpoints. The localPort of the client socket is 50261, which is the outbound port, and the localPort of the accepted socket at the server is 1234, which is the same as the port being listened at.
Have a look at the respective getRemotePort() values. You will see that the client's is 1234 and the server's is 50261, or rather that it agrees with the client's localPort, whatever it is next time you run it.
Neither threads move on from this point. What's going on here?
You need to construct the ObjectOutputStream before the ObjectInputStream, for reasons explained in the Javadoc and in many answers here, such as this one.

How to keep Socket Connection until Server Process it?

I am writing Socket program , Here Client Sends a String through Stream , Server Process it and writes back to Client. My problem is, after Server process the String , it Writes back to Stream but in client It can't able to read the Stream its showing exception as Exception in while: java.net.SocketException: socket closed Here is my code,
Client ,
public void run() {
while (true) {
try {
// Open your connection to a server, at port 1231
s1 = new Socket("localhost", 1231);
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
InputStream in=s1.getInputStream();
DataInputStream dis=new DataInputStream(in);
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
dos.close();
System.out.println(dis.readUTF());//it is the String from Server after processing
dis.close();
} catch (IOException ex) {
// Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Exception in while: " + ex);
}
}
In Server
public void run()
{
while(true){
try {
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
String clientData=dis.readUTF();
//processing task String
dos.writeUTF("Bus Registered Successfully");
dos.flush();
}
}
Here I am not able to read Bus Registered Successfully at client side . How to Solve this.?
Well there are many things not right in your program. But first let me answer your question ... you are closing the socket just after writing the stream ... so server throws exception, just remove dos.close(); just after the dos.flush();. It will run fine.
Now back to the programming practices ...
1) Server should accept the connection in a while(true) loop and then make a new thread. So following statement should not be the part of run method.
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
2) There is no need of run method in client. Because Every new client will be a new program that has its own variables and socket.
A quick look shows me that the reason the socket is closed is because you used dos.close().
Closing a DataInputStream (or PrintStream, or any similiar stream) will close the underlying socket.
Just take out dos.close().
You can also move the dos.close() to the very end of the try block. As a general rule, don't close anything related to the socket until you're done with the socket.

Error in receiving ObjectInputStream

I am trying to create a client server program where I'm sending an object from client and receiving the object at the server continuously in the while loop.
Client code:
ObjectOutputStream oos = null;
while(true){
WorkerMessageToMaster message = new WorkerMessageToMaster(WorkerTasksStatus.getTaskStatusMap(), WorkerTasksStatus.getTaskStatusReduce());
oos = new ObjectOutputStream(taskManagerSocket.getOutputStream());
oos.writeObject(message);
oos.flush();
Thread.sleep(1000);
}
Server code:
ObjectInputStream ois = null;
while (true ) {
ois = new ObjectInputStream(clientSocket.getInputStream());
WorkerMessageToMaster taskMapObject = (WorkerMessageToMaster)ois.readObject();
System.out.println("Connection from: "+clientSocket.getInetAddress().getHostAddress().toString());
}
When I try to run this code on my local system It runs normally, but when I try to run the client and server in different machines(different Ips) I get the following error.
java.io.StreamCorruptedException: invalid stream header: 74000432
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at master.MasterAnalyzer.heartBeat(MasterAnalyzer.java:58)
at master.MasterAnalyzer.run(MasterAnalyzer.java:80)
at java.lang.Thread.run(Thread.java:745)
I am confused at this erratic behavior as Im sending the stream through the client socket established with the server in a while loop and receiving it on the same socket connection accepted at the server and It seems to be working fine on local host.
Thank you for your help
You create a new stream for each object. Only create one output and one input stream. Object streams send header data which is maybe corrupted when you create a new stream.

Server-client file transfer null pointer exception

I'm developing a server to client file transfer program on java, and couldn't figure out how to fix the following code as I don't know much about socket programming. The code is Client side's codes:
String receiverIP = null;
int serverPort = 0;
hostIP = args[0];
serverPort = Integer.parseInt(args[1]);
String fileToSend = args[2];
byte[] aByte = new byte[1];
int bytesR;
Socket clientSocket = null;
Socket connectSocket = null;
BufferedOutputStream ToClient = null;
InputStream is = null;
try {
ToClient = new BufferedOutputStream(connectSocket.getOutputStream());
clientSocket = new Socket(hostIP, serverPort);
is = clientSocket.getInputStream();
} catch (IOException ex) {
System.out.println(ex);
}
as for my problem, I get a null pointer exception on line 14 (undoubtedly since currently connectSocket is null), but I have no idea what can I assign on connectSocket(if it was on server side a connection accept socket could've been assigned to begin writing after the connecion is established.)
Contrary to what you seem to believe, you do not need two separate sockets to read and write to the server. One socket will suffice. You can call the getInputStream method to get a stream to read from the server, and getOutputStream to get a stream to write to the server. You don't need two sockets, just one.

Unsure of Client Server IP configuration in Java

I have a written a simple Client-Server pair, sending an Object to the server. I have tested the code and it works, provided I use LOCALHOST as the server name.
When attempting to connect to the server using my own IP address, the client continuously times out. I cannot help thinking I've missed a trick, if someone could take a look at the code I would be very grateful. Many Thanks, J.
client
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
Socket socket = null;
Person p = null;
try {
// My IP address entered here..
socket = new Socket("xx.xx.xxx.xxx", 3000);
// open I/O streams for objects
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
/*
// read an object from the server
p = (Person) ois.readObject();
System.out.print("Name is: " + p.getName());
oos.close();
ois.close();*/
//write object to the server
// p = new Person("HAL");
oos.writeObject(new Person("HAL"));
oos.flush();
ois.close();
oos.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
Server
public Server() throws Exception {
server = new ServerSocket(3000);
System.out.println("Server listening on port 3000.");
this.start();
}
You either need to make your server bind to 0.0.0.0 (wildcard, all interfaces on your machine) or the specific IP you want it to listen on. The ServerSocket constructor you're using only takes a port number and binds to localhost which is going to resolve to 127.0.0.1
server = new ServerSocket(3000, 5, InetAddress.getByName("0.0.0.0"));
Edit to add: The second paramater is the backlog size. This is the number of connections that can be queued waiting for you to accept() them before additional connection attempts will result in "connection refused".

Categories

Resources