WebSocket服务端和客户端代码示例

Posted 小志的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebSocket服务端和客户端代码示例相关的知识,希望对你有一定的参考价值。

目录

一、WebSocket简介

  • WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信,即允许服务器主动发送信息给客户端。因此,在WebSocket中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输,客户端和服务器之间的数据交换变得更加简单。

二、WebSocket服务端代码示例

  • 服务端示例代码

    package com.worklite.out.socket;
    
    import lombok.extern.slf4j.Slf4j;
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * @description:
     * @author: xz
     */
    @Slf4j
    public class SocketServer extends Thread
        Socket socket = null;
    
        public SocketServer(Socket socket) 
            this.socket = socket;
        
    
        @Override
        public void run() 
            BufferedReader bufferedReader = null;
            PrintWriter writer = null;
            try 
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //true,表示自动刷新,不需要人为触发
                writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
    
                String userInput;
                while ((userInput = bufferedReader.readLine()) != null) 
                    if ("exit".equals(userInput)) 
                        log.info("短信socket服务端退出连接通信\\t");
                        break;
                    
                    log.info("短信socket服务端 接收内容:\\t" + userInput);
                    String result = "<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?><response>0000</response>";
                    writer.println(result);
                
             catch (IOException e) 
                e.printStackTrace();
             finally 
                try 
                    if (writer != null)
                        writer.close();
                    
                    if (bufferedReader != null) 
                        bufferedReader.close();
                    
                    if (socket != null) 
                        socket.close();
                    
                 catch (IOException ioException) 
                    ioException.printStackTrace();
                
            
        
    
        public static void main(String[] args) 
            try 
                //1.创建服务器端ServerSocket对象,指定端口
                ServerSocket serverSocket = new ServerSocket(64202);
                Socket socket = null;
                log.info("短信socket服务端等待客户端的连接");
                //2.调用accept()监听(即等待客户端的连接)
                while (true) 
                    socket = serverSocket.accept();
                    //创建一个新线程
                    SocketServer serverThread = new SocketServer(socket);
                    serverThread.start();
                
             catch (IOException e) 
                e.printStackTrace();
            
        
    
    
    

三、WebSocket客户端代码示例

  • 客户端示例代码

    package com.worklite.out.socket;
    
    import lombok.extern.slf4j.Slf4j;
    import java.io.*;
    import java.net.Socket;
    /**
     * @description:
     * @author: xz
     */
    @Slf4j
    public class SocketClient 
    
        public static String client(String reqXmlStr,String socketIp,int socketPort) 
            log.info("调用短信socket客户端,xml格式请求报文——>",reqXmlStr);
            Socket socket = null;
            BufferedReader bufferedReader = null;
            PrintWriter writer = null;
            String result = null;
            try 
                socket = new Socket(socketIp,socketPort);
    
                //发送数据到服务端
                writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
                writer.println(reqXmlStr);
    
                //接收服务端返回数据流
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while ((result = bufferedReader.readLine()) != null)
                    log.info("短信socket客户端接收服务端响应报文:",result);
                    //退出指令,关闭连接
                    writer.println("exit");
                    break;
                
            catch (IOException e) 
                log.info("[短信socket客户端异常]",e);
                e.printStackTrace();
             finally 
                try 
                    if (writer != null)
                        writer.close();
                    
                    if (bufferedReader != null) 
                        bufferedReader.close();
                    
                    if (socket != null) 
                        socket.close();
                    
                 catch (IOException e) 
                    log.info("[短信socket客户端流关闭异常]",e);
                    e.printStackTrace();
                
            
            return result;
        
    
        public static void main(String[] args) 
            String reqXmlStr="<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?><request><telnumber>13912345678</telnumber></request>";
            client(reqXmlStr,"localhost",64202);
        
    
    
    

四、运行服务端和客户端,查看输出结果

  • 先启动服务端,如下图所示:
  • 再启动客户端,如下图所示:
  • 再次查看服务端,如下图所示:

以上是关于WebSocket服务端和客户端代码示例的主要内容,如果未能解决你的问题,请参考以下文章

WebSocket服务端和客户端使用

SuperWebSocket实现服务端和WebSocket4Net实现客户端

使用WebSocket实现服务端和客户端的通信

C# WebSocket 服务端示例代码 + HTML5客户端示例代码

python 实现websocket

java socket编写服务端