0

我正在尝试发送一个对象,该对象将通过ObjectOutputStream使用套接字来保存一些信息。当我调用该方法Client_Handler(String auth, String user)并发送对象时它工作正常,但是当我再次调用它时它不起作用。我希望能够使用连接多次发送包含不同数据的对象。

客户:

public void Client_Handler(String auth, String user){
        try{
        socket2 = new Socket(serverAddress, 8080);
        User_Authorization us3 = new User_Authorization();
        ObjectOutputStream out2 = new ObjectOutputStream(socket2.getOutputStream());
        us3.set_name(user);
        us3.set_authorization(auth);
        out2.writeUnshared(us3);  
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        }  
}

服务器:

public class Conn implements Runnable{
private Socket socket;
public static ServerSocket server ;

public void go(){
    Thread r = new Thread(this);
        try{
                r.start();
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        }  
}

@Override
public void run() {
    try{
    server = new ServerSocket(8080);
    socket = server.accept(); 
    while(true){
        Login.User_Authorization us = null;            
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
        us = (Login.User_Authorization) in.readObject();
    System.out.println(us.get_name()+ "he's " +us.get_authorization());
   }
    }catch(Exception e){JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);}
}
4

1 回答 1

1

当我调用方法 Client_Handler(String auth, String user) 并发送对象时它工作正常,但是当我再次调用它时它不起作用。

因为,每次您调用Client_Handler(String auth, String user)方法时,您都在尝试与 Server 建立一个新连接,通过socket2 = new Socket(serverAddress, 8080);它来终止先前的连接。这就是为什么你得到EOFException例外。您应该socket2在调用Client_Handler方法之前创建一次对象。在调用该Client_Handler方法时,只需使用初始化的 Socket socket2

您的代码在客户端可能是这样的:

Socket socket2;
ObjectOutputStream out2 = null;
public void mainMethod()
{
    try
    {
        socket2 = new Socket(serverAddress, 8080);  
        out2 = new ObjectOutputStream(socket2.getOutputStream());
        boolean canSend = true;
        while (canSend)
        {
            canSend = Client_Handler("authentication","user");
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        if (out2!=null)
        {
            try
            {
                out2.close();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
}
public boolean Client_Handler(String auth, String user)
{
    try
    {
        User_Authorization us3 = new User_Authorization();
        us3.set_name(user);
        us3.set_authorization(auth);
        out2.writeUnshared(us3);  
    }catch(Exception e)
    {
        JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }  
    return true;
}
于 2013-06-26T19:05:50.300 回答