开发者

Why won't my server and client I coded in Java work?

开发者 https://www.devze.com 2022-12-14 01:50 出处:网络
My server keeps getting this error when I run the client: Exception in thread \"main\" java.io.EOFException

My server keeps getting this error when I run the client:

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
    at java.io.ObjectInputStream.readInt(Unknown Source)
    at MyServer.main(MyServer.java:10)

Here is the server code:

import java.net.*;
import java.io.*;

public class MyServer{
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(40);
        Socket clientSocket = serverSocket.accept();
        ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
        System.out.println(in.readInt());
        serverSocket.close();
        System.exit(0);
    }
}

And here is the client code:

import java.io.*;
import java.net.*;

public class MyClient {
    public static void main(String[] args) throws 开发者_如何学PythonIOException {

        Socket socket = new Socket("localhost", 40);
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());     
        out.writeInt(5);
        socket.close();
        System.exit(0);
    }
}


Try adding

out.flush();

just before

socket.close();


You should flush your ObjectOutputStream before closing the Socket.

0

精彩评论

暂无评论...
验证码 换一张
取 消