Java TCP协议传输

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

服务器端:

 1 import java.io.*;  
 2 import java.net.*;  
 3 public class TCPServer {  
 4   
 5     public static void main(String[] args) throws Exception{  
 6        ServerSocket s=new ServerSocket(8002);  
 7         while (true) {  
 8             Socket s1=s.accept();  
 9             OutputStream os=s1.getOutputStream();  
10             DataOutputStream dos=new DataOutputStream(os);  
11             dos.writeUTF("Hello, world");  
12             dos.close();  
13             s1.close();  
14               
15         }  
16     }  
17 }  

客户端:

 1 import java.io.*;  
 2 import java.net.*;
 3 public class TCPClient {  
 4   public static void main(String[] args) throws Exception{  
 5       Socket s1=new Socket("127.0.0.1", 8002);  
 6         InputStream is=s1.getInputStream();  
 7         DataInputStream dis=new DataInputStream(is);  
 8         System.out.println(dis.readUTF());  
 9         dis.close();  
10         s1.close();  
11           
12     }  
13 }  

运行结果:

 

posted @ 2017-12-14 18:15  浅笑Cc。  阅读(195)  评论(0编辑  收藏  举报