简体   繁体   English

在Java套接字中将对象从服务器发送到客户端

[英]send objects from server to client in java sockets

I want to send objects from the server to the client in java sockets. 我想在Java套接字中将对象从服务器发送到客户端。 I can send them from client to the server, however I am struggling to send them from server to client. 我可以将它们从客户端发送到服务器,但是我正努力将它们从服务器发送到客户端。 I am new to Java so I'm still learning the basics. 我是Java新手,因此仍在学习基础知识。 I know its something relatively minor that I need to do, however i am struggling with it at the moment. 我知道这是我需要做的相对较小的事情,但是目前我正为此而苦苦挣扎。 Can someone add the bits of code that i am missing? 有人可以添加我缺少的代码吗?

Open another connection in another thread and let the client be server, and server be client. 在另一个线程中打开另一个连接,让客户端成为服务器,而服务器成为客户端。 So in one thread you send A -> B, in another thread you open another socket and begin to send b B -> A. 因此,在一个线程中发送A-> B,在另一个线程中打开另一个套接字并开始发送b B->A。

The problem with low level sockets is that if one side is writing, the other should be listening. 低级别套接字的问题在于,如果一侧正在写,另一侧正在监听。 That means you have to implement command-query protocol, which is a heavy task. 这意味着您必须实现命令查询协议,这是一项繁重的任务。 So with my proposal you will use two ports but you know that you will have 2 pipes of data flow. 因此,根据我的建议,您将使用两个端口,但您知道将有2条数据流管道。

A --8888--> B
A <--8889-- B

It will be easier if you are just starting with sockets. 如果您只是从套接字开始,那会更容易。

You can use ObjectOutputStream to send an object through the socket and ObjectInputStream to receive one: 您可以使用ObjectOutputStream通过套接字发送一个对象,并使用ObjectInputStream接收一个对象:

private ObjectOutputStream oos; 
private ObjectInputStream ois;

public SocketHandler(Socket cs) {
    this.oos = new ObjectOutputStream(cs.getOutputStream());
    this.ois = new ObjectInputStream(cs.getInputStream());
}

public void sendObject(Object o) {
    this.oos.writeObject(o);
    this.oos.flush();
}

public Object receiveObject() {
    return this.ois.readObject();
}

That was assuming you want to send and receive an Object. 那是假设您要发送和接收一个对象。 You can also use PrintWriter and BufferedReader to send and receive String messages and after parsing it: 您还可以使用PrintWriterBufferedReader来发送和接收String消息,并在解析之后:

private PrintWriter pw;
private BufferedReader br;

public SocketHandler(Socket cs) {
    this.pw = new PrintWriter(cs.getOutputStream());
    this.br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
}

public void sendMsg(String msg) {
    this.pw.println(msg);
    this.pw.flush();
}

public String receiveMsg() {
    return this.br.readLine();
}

Below I have an example of some Server-Side code that I used for an application a while ago, then I will give you an explanation as to what's going on here: 下面是一个示例,其中有一些我之前在应用程序中使用过的服务器端代码的示例,然后我将向您解释此处的情况:

first you need to create your ServerSocket in order to accept client requests (as you already know): 首先,您需要创建ServerSocket才能接受客户端请求(如您所知):

ServerSocket serverSocket = new ServerSocket(1002);
        while(true) {

Then you need to enter a while loop in order to receive requests for as long as the Server program is alive 然后,只要服务器程序处于活动状态,就需要进入while循环以便接收请求

Socket clientSocket = serverSocket.accept();
System.out.println("Connection made to: " + clientSocket);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String messageString = "";
String line;
System.out.println("Enter while loop to retrieve client message...");
while((line = br.readLine()) != null) {
        String clientRequestLine = line;
        if(clientRequestLine.contains("check return user credentials")) {
        String userNamePassWord = clientRequestLine.replace("check return user credentials", "");
        userNamePassWord = userNamePassWord.trim();
        String[] userNamePassWordSplitter = userNamePassWord.split(" ");
        String userName = userNamePassWordSplitter[0];
        String passWord = userNamePassWordSplitter[1];
        System.out.println("Username: " + userName + "\nPassword: " + passWord);
            boolean isValidUserNamePassWord = ReturnPatientCredentials.checkUserNamePassWord(userName, passWord);
        if(isValidUserNamePassWord) {
                System.out.println("valid");
                out.println("valid");
                    }
        else {
                System.out.println("invalid");
                out.println("invalid");
                    }
                }

Above you need to start a BufferedReader in order to store an InputStream (the data) from the client socket. 在上面,您需要启动BufferedReader以便从客户端套接字存储InputStream(数据)。 You also need to create a PrintWriter so that you can send data to the OutputStream and you need to pass your clientSocket as the argument for the OutputStream. 您还需要创建一个PrintWriter,以便可以将数据发送到OutputStream,并且需要将clientSocket作为OutputStream的参数传递。 Next you'll create variables to get the message and the "line" of date from the client and enter a while loop. 接下来,您将创建变量以从客户端获取消息和日期的“行”,并进入while循环。 You can then store the line in a variable and read the data or whatever you need to do. 然后,您可以将行存储在变量中,并读取数据或您需要执行的任何操作。 We use our PrintWriter (out) to send data back with the println() method and then we can break out of the loop when needed. 我们使用PrintWriter(out)通过println()方法将数据发送回去,然后在需要时可以跳出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM