liuzhen6835
liuzhen6835
2015-05-12 06:03
采纳率: 51.2%
浏览 2.1k
已采纳

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • qq_22002307
    qq_22002307 2015-05-13 12:09
    已采纳

    可以利用多线程, 服务器端不断接收客户端连接, 连接一个就开一个线程处理 客户端的交互,

    点赞 评论
  • wojiushiwo945you
    毕小宝 2015-05-12 07:01

    这里有一个简单的例子,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();
        }
    }
    
    点赞 评论

相关推荐