开发者社区> 问答> 正文

Java中的Socket服务中如何实现客户端和服务端多次通讯

比如,服务器给客户端发一个信息。然后服务端根据客户端发送的信息判断,再回复一个信息,就是多次读和写的问题

展开
收起
蛮大人123 2016-03-12 16:45:39 6262 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    可以利用多线程, 服务器端不断接收客户端连接, 连接一个就开一个线程处理 客户端的交互,
    这里有一个简单的例子,Client端发送消息给Server端,并读取Server端的回复信息;而Server端则先读取Client端的数据,再回复数据。
    Server端:

     public class Main {
        public static void main(String[] args) {
            ServerSocket server;
            try {
                server = new ServerSocket(8800);
                System.out.println("Wait for connection...");
                Socket socket = server.accept();
                BufferedInputStream is = new BufferedInputStream(
                        socket.getInputStream());
                byte[] buff = new byte[1024];
                int size;
                while ((size = is.read(buff)) != -1) {
                    System.out.println(new String(buff, 0, size));
                }
    
                OutputStream os = socket.getOutputStream();
                os.write("您好,我是Server端".getBytes());
                os.flush();
                os.close();
                System.out.println("ok,client send over.");
                server.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Client端:

    public class Client {
        public static void main(String[] args) throws Exception 
        {
            Socket s = new Socket("localhost",8800);
            OutputStream os = s.getOutputStream();
            os.write("您好,我是客户端".getBytes());
            os.close();
    
            InputStream in = s.getInputStream();
            byte[] buff = new byte[1024];
            BufferedInputStream is = new BufferedInputStream(in);
            int size;
            while((size = is.read(buff)) != -1){
                System.out.println(new String(buff,0,size));
            }
            System.out.println("over...");
            s.close();
        }
    }
    2019-07-17 19:01:12
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载