码迷,mamicode.com
首页 > 编程语言 > 详细

Java TCP协议传输

时间:2017-12-14 19:14:27      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:throw   tao   images   main   pre   协议   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 }  

运行结果:

技术分享图片

 

Java TCP协议传输

标签:throw   tao   images   main   pre   协议   tcp   建立   传输   

原文地址:http://www.cnblogs.com/songqinzhe/p/8039132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!