当前位置: 代码迷 >> 综合 >> Java开发练习9.2 TCP
  详细解决方案

Java开发练习9.2 TCP

热度:46   发布时间:2024-01-19 22:37:40.0

使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello,world”,客户端收到数据后打印输出。

public class tcp {  public static void main(String[] args) {  // TODO Auto-generated method stub  try{  ServerSocket s = new ServerSocket(8002);  while(true){  Socket s1 = s.accept();  OutputStream os = s1.getOutputStream();  DataOutputStream dis = new DataOutputStream(os);  dis.writeUTF("Hello,wrold!");  dis.close();  s1.close();  }             }catch(Exception e){  e.printStackTrace();  }  }  }  public class tcpclient {  public static void main(String[] args) {  // TODO Auto-generated method stub  try{  Socket s1 = new Socket("127.0.0.1", 8002);  InputStream is = s1.getInputStream();  DataInputStream dos= new DataInputStream(is);  System.out.println(dos.readUTF());  dos.close();  s1.close();  }catch(Exception e){  e.printStackTrace();  }  }  }