java-网络编程基础入门

    科技2024-05-25  76

    //服务器端代码 public class ServerTCP { public static void main(String[] args) { int port = 8888; ServerSocket server = null; Socket socket = null; try { server = new ServerSocket(port); System.out.println(“服务器启动,监听端口”+port+",等待客户端的socket = server.accept(); System.out.println(“服务器接收到客户端的连接:”+socket); } catch (IOException e) { e.printStackTrace(); }finally { //关闭资源 if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(server!=null){ try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } } } //客户端代码 public class ClientTCP { public static void main(String[] args) { String host = “127.0.0.1”; int port = 8888; Socket socket = null; try { //对象创建成功,就表示连接服务器端成功 socket = new Socket(host,port); } catch (IOException e) { e.printStackTrace(); }finally { //关闭资源 if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

    Processed: 0.015, SQL: 8