简体   繁体   中英

After successfully establishing a socket connection, how does the server actively send string messages to the client?

I am building a server. I hope that after the Java server and the C# client are connected, I can send information from the HTML to the Java server, and then the Java server sends this information to the client.But I can't get the socket after the successful establishment in the service layer, so my Java server can only send fixed information to the client.

I tried using Class object = new Class(); object.setObject(socket); to save the socket, but when I call this object in the service layer, I get null; I tried to save the socket using (Map) socket.put("socket", socket), but when I call this method in the service layer, I get null.

This is the code to make the socket. from SocketThread.java

    public void run() {
        ServerSocket serverSocket = null;
        try{
            serverSocket = new ServerSocket(5656);
            LOGGER.info("socket server start, monitor 5656 port ! ");
            Socket socket = serverSocket.accept();
            new SocketClientRequest(socket).start();
            LOGGER.info("send success ! ");
        }catch (Exception ex){
            LOGGER.error("send fail ! ");
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            LOGGER.error("服务器延时重启失败 ! ");
        }
    }

This is a method of reading the information sent by the client using the socket and sending the information to the client. from SocketClientRequest.java

public void run() {
        try {
            //获取socket中的数据
            bufferedInputStream = new 
            BufferedInputStream(socket.getInputStream());
            byte[] clientCharStream = new byte[messageLengthBytes];

            bufferedInputStream.read(clientCharStream);
            System.out.println(new String(clientCharStream, "utf-8"));

            OutputStream out = socket.getOutputStream();
            out.write(new String("welcome_send_server!").getBytes());
        } catch (IOException e) {
            LOGGER.error("read massage error [{}]", e);
        }
    }

Create a connection when the project starts

@EnableScheduling
@SpringBootApplication
public class GzserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(GzserverApplication.class, args);

        SocketServer socketServer = new SocketServer();
        socketServer.start();
    }

}

Until this step, everything is fine, but the key problem is coming. I need to send information to the client through my controller. this is controller

    @ResponseBody
    @RequestMapping(value = "firstSend)
    public SResult<String> firstSend(String uName, String pNum, String time){
        try{
            return httpService.firstSend(uName, pNum, time);
        }catch (Exception ex){
            LOGGER.error(ex.getMessage(), ex);
        }
        return SResult.failure("fail of connect");
    }
this is service
    public SResult<String> firstSend(String uName, String pNum, String time) throws Exception {
        String token = TokenUtil.sign(uName);
        System.out.println("token code : "+token);

        SocketObject socketObject = new SocketObject();
        Map<String, Socket> socketMap = socketObject.socket();
        Socket socket1 = socketMap.get("Socket"); // is null
        Socket socket2 = socketObject.getSocket(); // is null

        return SResult.success(token);
    }

I hope that after the connection is successfully created, the socket can be used in the service layer, and the information is sent to the client through the socket, but no matter what I do, the socket is null in the service layer.please give me a help, thank you very much

You should not be dealing with Socket s if using Spring. Spring is a very extensive abstraction layer, that lets you avoid having to deal with the nasty details that Socket s introduce.

In your controller, you call: SocketObject socketObject = new SocketObject(); This creates a new object, presumably with a null -initialized Socket object. Nowhere in this code do you pass a socket object from the main() scope to any other scope (for example using a method named setSocket(Socket socket) .

However, and I cannot stress this enough, you should not use Socket s in Spring. Think about what problem you are trying to solve, and ask yourself (why do I need to send information to the client). It is likely that Spring has a module that will do this for you in a much more scalable and manageable way.

For example, perhaps you need to establish 2-way communication between the server and the client, and need to post information to the client periodically. In this case, the WebSocket protocol (and associated Spring Websocket library) might be for you.

This is likely an XY problem . If you edit your question to illustrate the functionality you are trying to implement, it may be easier to help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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