java socket保持长连接

ServerSocket serverSocket=new ServerSocket(1111);
Socket socket=serverSocket.accept();
while(true){//保持长连接
   	try {
       		Thread.sleep(100);//等待时间
   	} catch (InterruptedException e1) {
       		e1.printStackTrace();
   	}
	if (socket !=null){
   		try {
      			String ip = socket.getInetAddress().toString().replace("/", "");
   	      		System.out.println("====socket.getInetAddress()====="+ip);
          		socket.setKeepAlive(true);
          		InputStream is = socket.getInputStream();
          		OutputStream os = socket.getOutputStream();
          		System.out.println("服务器端接受请求");
			String tempdata = StreamEazyUse.getContent(is);
			system.out.printl(“接收到的数据为:”+tempdata);
			if(tempdata.contains(“stop”)){
				is.close();
				os.close();
			}
			os.flush();
		}catch(Exception e){
			system.out.println(“出现了错误”);
		}
	}
}


你可能感兴趣的:(java socket保持长连接)