Java TCP协议传输

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

服务器端:服务器

 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 }  

运行结果:spa

相关文章
相关标签/搜索