TCP通信

来源:互联网 发布:剑3成女捏脸数据 编辑:程序博客网 时间:2024/06/08 11:24
    使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002。 
    当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。 

1.TCPServer.java
import java.io.DataOutputStream;  import java.io.OutputStream;  import java.net.ServerSocket;  import java.net.Socket;    public class TCPServer {        public static void main(String[] args) throws Exception{                    ServerSocket s=new ServerSocket(8002);          while (true) {              Socket s1=s.accept();              OutputStream os=s1.getOutputStream();              DataOutputStream dos=new DataOutputStream(os);              dos.writeUTF("Hello, world");              dos.close();              s1.close();                        }      }  }  
2.TCPClient.java
import java.io.DataInputStream;  import java.io.InputStream;  import java.net.Socket;    public class TCPClient {        public static void main(String[] args) throws Exception{                Socket s1=new Socket("127.0.0.2", 8002);          InputStream is=s1.getInputStream();          DataInputStream dis=new DataInputStream(is);          System.out.println(dis.readUTF());          dis.close();          s1.close();       }  }  
3.运行截图