一旦建立了连接,服务端和客户端就可以通过Socket进行通信了 1. 客户端打开输出流,并发送数字 110 2. 服务端打开输入流,接受数字 110,并打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package socket; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { try { Socket s = new Socket( "127.0.0.1" , 8888 ); // 打开输出流 OutputStream os = s.getOutputStream(); // 发送数字110到服务端 os.write( 110 ); os.close(); s.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package socket; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket( 8888 ); System.out.println( "监听在端口号:8888" ); Socket s = ss.accept(); //打开输入流 InputStream is = s.getInputStream(); //读取客户端发送的数据 int msg = is.read(); //打印出来 System.out.println(msg); is.close(); s.close(); ss.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |