TCP之socket
分享一个TCP下的socket小栗子
客户端:
1 package com.TCP.socket; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.io.OutputStreamWriter; 9 import java.io.PrintWriter; 10 import java.net.Socket; 11 12 /** 13 * Client端应用程序 14 */ 15 public class Client2 { 16 public static void main(String[] args) { 17 Socket socket = null; 18 try { 19 socket = new Socket("localhost",8088);//参数1:服务端的IP地址,参数2:服务端的服务端口 20 //获取输入流,用于读取来自服务端的消息 21 InputStream in = socket.getInputStream(); 22 BufferedReader reader = new BufferedReader( 23 new InputStreamReader(in,"UTF-8") 24 ); 25 26 //获取输出流,用于向服务端发送消息 27 OutputStream out = socket.getOutputStream(); 28 OutputStreamWriter osw = new OutputStreamWriter(out,"UTF-8"); 29 PrintWriter writer = new PrintWriter(osw,true); 30 31 //向服务端发送一个字符串 32 writer.println("你好服务器!"); 33 34 //读取来自客户端发送的消息 35 String message = reader.readLine(); 36 System.out.println("服务器说:"+message); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } finally{ 40 try { 41 if(socket != null){ 42 //关闭Socket 43 socket.close(); 44 } 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } 48 } 49 } 50 }
服务端:
1 package com.TCP.socket; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.io.OutputStreamWriter; 9 import java.io.PrintWriter; 10 import java.net.ServerSocket; 11 import java.net.Socket; 12 13 /** 14 * Server端应用程序* 15 */ 16 public class Server2 { 17 public static void main(String[] args) { 18 ServerSocket server = null; 19 try { 20 //创建ServerSocket并申请服务端口为8088 21 server = new ServerSocket(8088); 22 23 while(true){ 24 //循环侦听客户端的连接 25 /*方法会产生阻塞,直到某个Socket连接,并返回请求连接的Socket*/ 26 Socket socket = server.accept(); 27 //当一个客户端连接后,启动线程来处理该客户端的交互 28 new ClientHandler(socket).start(); 29 } 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } finally{ 33 if(server != null){ 34 try { 35 server.close(); 36 } catch (IOException e) { 37 } 38 } 39 } 40 } 41 } 42 /** 43 * 线程类 44 * 该线程的作用是并发与客户端进行交互 45 * 这里的代码就是原来在Server中客户端连接后交互的代码 46 */ 47 class ClientHandler extends Thread{ 48 private Socket socket; 49 public ClientHandler(Socket socket){ 50 this.socket = socket; 51 } 52 public void run(){ 53 try { 54 //获取输入流,用于读取客户端发送过来的消息 55 InputStream in = socket.getInputStream(); 56 BufferedReader reader 57 = new BufferedReader( 58 new InputStreamReader( 59 in,"UTF-8" 60 ) 61 ); 62 63 //获取输出流,用于向该客户端发送消息 64 OutputStream out = socket.getOutputStream(); 65 PrintWriter writer 66 = new PrintWriter( 67 new OutputStreamWriter( 68 out,"UTF-8" 69 ),true 70 ); 71 72 //读取客户端发送的消息 73 String message = reader.readLine(); 74 System.out.println("客户端说:"+message); 75 76 //向客户端发送消息 77 writer.println("你好客户端!"); 78 } catch (Exception e) { 79 e.printStackTrace(); 80 } 81 } 82 }