java网络编程之socket
基于tcp双向传输,socket编程共用信息流来接收和发送数据。
重点在于理解对不同端来说,输入与输出流的关系。对客户端来说,服务端的输出是客户端的输入。
对服务端来说,客户端的输出是服务端的输入。
import java.io.*; import java.net.*; public class Client { public static void main(String args[]) throws Exception { //为了简单起见,所有的异常都直接往外抛 String host = "127.0.0.1"; //要连接的服务端IP地址 int port = 8899; //要连接的服务端对应的监听端口 //与服务端建立连接 Socket client = new Socket(host, port); //建立连接后就可以往服务端写数据了 BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream())); BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); PrintWriter os = new PrintWriter(client.getOutputStream()); String s; s = sin.readLine(); os.println(s); os.flush(); System.out.println("Server:"+is.readLine()); os.close(); is.close(); client.close(); } }
1 import java.io.*; 2 import java.net.*; 3 4 public class Server { 5 6 public static void main(String args[]) throws IOException { 7 //端口 8 int port = 8899; 9 //建立服务端socket 10 ServerSocket server = new ServerSocket(port); 11 Socket socket = server.accept(); 12 13 BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); 14 15 PrintWriter os = new PrintWriter(socket.getOutputStream()); 16 17 BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); 18 19 String s = is.readLine(); 20 //获取客户端的输入流 21 System.out.println("client:"+s); 22 if(s.equals("hello")){ 23 os.println("你好"); 24 os.flush(); 25 }else{ 26 System.out.println("bye"); 27 } 28 29 30 is.close(); 31 os.close(); 32 socket.close(); 33 server.close(); 34 } 35 36 }