传统的java实现socket通讯比较简单实现,不过它属于堵塞式的I/O流存取,只能由一个线程完成当前任务才能起下个一个线程,无法解决高并发;
1、简单的socketservice
对每一个Socket连接建立一个Handler处理线程,处理线程对inputstream流中的数据进行相应的处理后,将处理结果通过PrintWriter发送给客户端,在最后需要关闭输入流、输出流和socket套接字句柄资源。
1 public class TimeServer { 2 3 public static void main(String[] args) throws IOException { 4 5 int port = 8080;//server 端口采用8080 6 ServerSocket server = null; 7 Socket socket = null; 8 try { 9 server = new ServerSocket(port); 10 while(true){ 11 socket = server.accept(); 12 new Thread(new TimeHandler(socket)).start(); 13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 }finally{ 17 if(server!=null){ 18 server.close(); 19 server =null; 20 System.out.println("the time server close..."); 21 } 22 } 23 } 24 25 } 26 27 class TimeHandler implements Runnable{ 28 29 private Socket socket; 30 31 public TimeHandler(){ 32 33 } 34 public TimeHandler(Socket socket){ 35 this(); 36 this.socket = socket; 37 } 38 39 public void run() { 40 System.out.println(Thread.currentThread().getName()+" start success..."); 41 BufferedReader in = null; 42 PrintWriter out = null; 43 try { 44 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 45 out = new PrintWriter(socket.getOutputStream(),true); 46 while(true){ 47 String str = in.readLine(); 48 if("end".equals(str)){ 49 break; 50 } 51 String time = str+":"+System.currentTimeMillis(); 52 out.println(time); 53 } 54 } catch (Exception e) { 55 e.printStackTrace(); 56 }finally{ 57 if(in!=null){ 58 try { 59 in.close(); 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 in = null; 64 } 65 if(out!=null){ 66 out.close(); 67 out= null; 68 } 69 if(socket!=null){ 70 try { 71 socket.close(); 72 } catch (IOException e) { 73 e.printStackTrace(); 74 } 75 socket =null; 76 } 77 } 78 79 } 80 }
2、socketclient
1 public class TimeClient { 2 3 public static void main(String[] args) { 4 int port = 8080; 5 Socket socket = null; 6 BufferedReader in =null; 7 PrintWriter out =null; 8 9 try { 10 socket = new Socket("127.0.0.1", port); 11 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 12 out = new PrintWriter(socket.getOutputStream(),true); 13 out.println("hello"); 14 out.println("world"); 15 out.println("end"); 16 17 System.out.println("send message success..."); 18 while(true){ 19 String res = in.readLine(); 20 if("".equals(res)||res==null){ 21 break; 22 } 23 System.out.println("the res is:"+res); 24 } 25 26 27 } catch (Exception e) { 28 e.printStackTrace(); 29 }finally{ 30 if(in!=null){ 31 try { 32 in.close(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 in = null; 37 } 38 if(out!=null){ 39 out.close(); 40 out= null; 41 } 42 if(socket!=null){ 43 try { 44 socket.close(); 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } 48 socket =null; 49 } 50 } 51 52 } 53 54 }
原文地址:https://www.cnblogs.com/ananaini/p/9446000.html
时间: 2024-11-06 09:44:15