new ServerSocket(int)是开启监听端口,并不是连接端口。真正的连接端口是随机开辟的空闲端口,当连接创建完成后,监听关口可以继续等待下一次连接请求,处于空闲等待状态。
编程实现方式
1 、主线程一直处于阻塞等待状态,如果一旦链接成功则启动一个新线程对外提供服务。
2 、启动工作线程时将链接对象 Socket 传递过去,在 run 方法中执行处理逻辑。
服务器编程实现
public class MyServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(9000);while (true){Socket scoket = serverSocket.accept();new WorkThread(scoket).start();}}
}
class WorkThread extends Thread{private Socket scoket;public WorkThread(Socket scoket){this.scoket = scoket;}@Overridepublic void run() {try {InputStream is = scoket.getInputStream();OutputStream os = scoket.getOutputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));PrintWriter out = new PrintWriter(os);String str = br.readLine();out.println("收到"+str);out.flush();out.close();br.close();scoket.close();} catch (IOException e) {System.out.println(e.getMessage());}}
}
客户端编程实现
public class MyClient {public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("你想给服务器说:");String str1 = br.readLine();Socket socket = new Socket("localhost",9001);System.out.println(socket.getInetAddress());System.out.println(socket.getPort());InputStream is = socket.getInputStream();OutputStream os = socket.getOutputStream();BufferedReader br2= new BufferedReader(new InputStreamReader(is));PrintWriter out = new PrintWriter(os);out.println(str1);out.flush();String str2 = br2.readLine();System.out.println(str2);br2.close();out.close();br.close();}
}