socket长连接例子(server&client)

最近做了一个测试,写了一个简单的socket长连接的测试例子,下面是代码

SocketServer.java

package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

	public static void main(String[] args) throws IOException {
	    ServerSocket serverSocket=new ServerSocket(1111);  
	    Socket socket=serverSocket.accept();  
	    while(true){//保持长连接  
	        try {  
	                Thread.sleep(3000);//等待时间  
	        } catch (InterruptedException e1) {  
	                e1.printStackTrace();  
	        }  
	        if (socket !=null){  
	        	InputStream is = null;
	        	OutputStream os = null;
	            try {  
                    String ip = socket.getInetAddress().toString().replace("/", "");  
                    System.out.println("====socket.getInetAddress()====="+ip);  
                    socket.setKeepAlive(true);  
                    is = socket.getInputStream();  
                    os = socket.getOutputStream();  
                    System.out.println("服务器端接受请求");  
	                byte[] buff = new byte[5];
	                is.read(buff);
	                String tempdata =new String(buff);  // StreamEazyUse.getContent(is);  
	                if (tempdata.equals("quit1")) {
	                	System.out.println("不处理,继续::"+tempdata); 
	                	continue;
	                }
	                System.out.println("接收到的数据为:"+tempdata);  
	                
	                os.write("world".getBytes());
	                os.flush();  //发送响应 
//	                is.close();
//	                os.close();
	            }catch(Exception e){  
	                System.out.println("出现了错误,关闭连接");
	                if (is!= null)
	                	is.close();
	                if (os!= null)
	                	os.close();
	                
	                e.printStackTrace();
	                
	            }  
	        }  
	    }  

	}

}

 SocketClient:

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {

	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket socket = new Socket("localhost",1111);
		if (socket.isConnected()){
			OutputStream os =null;
			InputStream is = null;
			while (true) {
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
					String in = br.readLine();
					os = socket.getOutputStream();
					os.write(in.getBytes());//"hello".getBytes());
					os.flush();
					
					is = socket.getInputStream();
					byte[] resp = new byte[5];
					is.read(resp);
					System.out.println("response:" + new String(resp));
				} catch (Exception e) {
					e.printStackTrace();
					if(os != null)
						os.close(); //由于是长连接,抛异常时要关闭os,否则会broken pipe
					if(is != null)
						is.close();
				} finally {
					System.out.println("do nothing");
				}
				
			}
		}

	}

}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值