import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerStringTest { public static void main(String[] args) { ServerSocket ss = null; Socket s = null; try { ss = new ServerSocket(8888); System.out.println("等待客户端的连接请求....."); s = ss.accept(); System.out.println("客户端连接成功!"); } catch (IOException e) { e.printStackTrace(); } finally { if (null != s) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } if (null!= ss) { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
import java.io.IOException; import java.net.Socket; public class ClientStringTest { public static void main(String[] args) { //创建Socket类型的对象并提供服务器的主机名和端口号 Socket s = null; try { s = new Socket("127.0.0.1", 8888); System.out.println("连接服务器成功!"); } catch (IOException e) { e.printStackTrace(); } finally { if (null !=s) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } } } }