Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ObjectOutputStream和线程的Java-TCP客户机/服务器_Java_Tcp_Client Server_Objectoutputstream - Fatal编程技术网

使用ObjectOutputStream和线程的Java-TCP客户机/服务器

使用ObjectOutputStream和线程的Java-TCP客户机/服务器,java,tcp,client-server,objectoutputstream,Java,Tcp,Client Server,Objectoutputstream,我试图开发某种聊天应用程序(学习目的),但当我将对象从客户端发送到服务器时,似乎只收到第一个对象。没有显示错误或什么都没有,所以我真的不知道出了什么问题 服务器代码: import chattychat.domain.Message; import chattychat.domain.User; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import ja

我试图开发某种聊天应用程序(学习目的),但当我将对象从客户端发送到服务器时,似乎只收到第一个对象。没有显示错误或什么都没有,所以我真的不知道出了什么问题

服务器代码:

import chattychat.domain.Message;
import chattychat.domain.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

 /**
 *
 * @author 
 */

public class Server {
private final int PORT;

private ServerSocket server;

public Server(){
    this.PORT = 6565;
}

public Server(int port){
    this.PORT = port;
}


public void listenSocket(){
    try{
        this.server = new ServerSocket(this.PORT);
    } catch (IOException e) {
        System.out.println("Could not listen on port 4444");
        System.exit(-1);
    }
    while(true){
        ClientWorker w;
        try{
            //server.accept returns a client connection
            w = new ClientWorker(server.accept());
            Thread t = new Thread(w);
            t.start();
        } catch (IOException e) {
            System.out.println("Accept failed: 4444");

        }
    }
}

class ClientWorker implements Runnable {
    private Socket client;
    private ObjectInputStream in;

    //Constructor
    ClientWorker(Socket client) {
        this.client = client;
    }

    public void run(){
        try{
            this.in = new ObjectInputStream(this.client.getInputStream());
            Object obj = this.in.readObject();
            System.out.println("called");
            if(obj instanceof Message){
                Message msg = (Message)obj;
                System.out.println(msg);
            }else if(obj instanceof User){
                User user = (User)obj;
                System.out.println(user);
            }
            System.out.println();
        }catch (IOException e) {
            System.out.println("Read failed");
            //System.exit(-1);
        } catch (ClassNotFoundException ex) {
            System.out.println("Object not found");
            //System.exit(-1);
        }
    }
}

@Override
protected void finalize(){
    try{
        this.server.close();
    } catch (IOException e) {
        System.out.println("Could not close socket");
        System.exit(-1);
    }
}

public static void main(String[] args){
    Server s = new Server();
    //s.communicate();
    s.listenSocket();
}
}

客户端代码:

import chattychat.domain.Message;
import chattychat.domain.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 *
 * @author laurensputseys
 */
public class Client {

    private final int PORT = 6565;
    private String SERVER = "localhost";

    private Socket socket;
    private ObjectInputStream in;
    private ObjectOutputStream out;
    private boolean isConnected;

    public Client(){
        this.isConnected = false;
    }

    public Client(String server){
        this.SERVER = server;
    }

    public String getServer(){
        return this.SERVER;
    }

    public int getPort(){
        return this.PORT;
    }

    public void communicate(Message msg){
        while(!isConnected){
            try{
                this.socket = new Socket(this.getServer(), this.getPort());
                isConnected = true;
                this.out = new ObjectOutputStream(this.socket.getOutputStream());
                this.out.writeObject(msg);
                this.out.flush();
                this.out.close();
            }catch(SocketException se){
                se.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    public void register(User usr){
        while(!isConnected){
            try{
                this.socket = new Socket(this.getServer(), this.getPort());
                isConnected = true;
                this.out = new ObjectOutputStream(this.socket.getOutputStream());
                this.out.writeObject(usr);
                this.out.flush();
                this.out.close();
            }catch(SocketException se){
                se.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    public boolean isConnected(){
        return isConnected;
    }

    public static void main(String[] args){
        Client c = new Client();
        User u1 = new User("firstname 1", "lastname1", "testuser");
        User u2 = new User("firstname 2", "lastname2", "Testuser");
        Message m1 = new Message(u1, u2, "Hello from P1 to P2");
        Message m2 = new Message(u2, u1, "Hello from P2 to P1");
        System.out.println("Send 1");
        c.communicate(m1);
        System.out.println("Send 2");
        c.communicate(m2);
        System.out.println("Send 3");
        c.register(u1);
    }
}
消息类:

import java.io.Serializable;
import java.util.Objects;

/**
 *
 * @author 
 */
public class Message implements Serializable{

    private static final long serialVersionUID = 7526472295622776147L;
    private User from;
    private User to;
    private String message;

    public Message(User from, User to, String message){
       this.setFrom(from);
       this.setTo(to);
       this.setMessage(message);
    }

    private void setFrom(User from){
        this.from = from;
    }

    private void setTo(User to){
        this.to = to;
    }

    private void setMessage(String message){
        this.message = message;
    }

    public String getMessage(){
        return this.message;
    }

    @Override
    public boolean equals(Object o){
        if(this == o) return true;
        if(o == null || getClass() != o.getClass()) return false;
        Message tmpMsg = (Message)o;
        return this.to.equals(tmpMsg.to) && this.from.equals(tmpMsg.from) && this.getMessage().equals(tmpMsg.getMessage());
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + Objects.hashCode(this.from);
        hash = 59 * hash + Objects.hashCode(this.to);
        hash = 59 * hash + Objects.hashCode(this.message);
        return hash;
    }

    @Override
    public String toString(){
        return "From: " + this.from + " to: " + this.to + " message: " +this.getMessage();
    }
}
用户类别:

import java.io.Serializable;
import java.util.Objects;

/**
 *
 * @author
 */
public class User implements Serializable{

    private static final long serialVersionUID = 7526456787322776147L;
    private String firstname;
    private String lastname;
    private String password;

    public User(String firstname, String lastname, String password){
        setFirstname(firstname);
        setLastname(lastname);
        setPassword(password);
    }

    private void setFirstname(String firstname){
        this.firstname = firstname; //TODO
    }

    private void setLastname(String lastname){
        this.lastname = lastname; //TODO
    }

    private void setPassword(String password){
        this.password = password; //TODO
    }

    @Override
    public boolean equals(Object o){
        if(this == o) return true;
        if(o == null || getClass() != o.getClass()) return false;
        User tmpUser = (User)o;
        return this.firstname.equals(tmpUser.firstname) && this.lastname.equals(tmpUser.lastname);
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + this.firstname.length();
        hash = 59 * hash + this.lastname.length();
        hash = 59 * hash + this.password.length();
        return hash;
    }

    @Override
    public String toString(){
        return this.firstname + " " + this.lastname;
    }
}

提前谢谢

没有彻底阅读您的代码。您的客户端在第一次调用时将连接到true的方法集进行通信。因此,在第二次调用通信时不会进入while循环。您应该将连接到服务器和发送消息分开。此外,服务器中的客户端工作线程似乎在读取一个对象后返回。run方法应该在连接断开时返回,而不是在读取一条消息时返回。

调试您自己的代码告诉了您什么?我的意思是你来这里之前已经试过先调试了,对吧?是的,但我看不到奇怪的行为,只是服务器只得到一个对象。在我看来,你没有调试过,否则你会告诉我们你的代码挂起的确切位置,而不是期望我们为你这么做。问题是,代码运行没有任何问题,我的变量得到了正确的信息。唯一的问题是我的客户只收到一个对象。但是当我为每个命令实例化客户机时,我就会得到我发送的所有对象。所以你还没有调试它,你的代码不能正常工作。为什么要撒谎?我们可以看穿它是的,真的,我真蠢!第二句话,你能不能再多给我一点关于你将如何实现这一点的信息?我将如何实现这一点是非常困难的。取决于我要解决的问题。我可能会使用第三方的东西,比如netty和protobuf。你在正确的轨道上。只需将客户端连接到服务器和发送消息分开即可。让服务器运行方法循环并读取对象,直到关机。感谢您的帮助!