网络编程-TCP程序实例(client端heserver端相互通信)

 1 package com.yyq;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.InetAddress;
 7 import java.net.Socket;
 8 
 9 
10 /*
11  * 演示tcp的传输的客户端和服务端的互访
12  * 需求:客户端给服务端发送数据服务端获取信息后给客户端回送数据
13  */
14 /*
15  * 客户端
16  *  1.建立socket服务。指定要接收主机和端口
17  *  2.获取socket流中的输出流,将数据写入到该六种,通过网络发送到服务器
18  *  3.获取socket流中的输入流,将服务端反馈的数据获取到,并打印
19  *  4.关闭客户端资源。
20  * 
21  */
22 public class TcpClient2 {
23     public static void main(String[] args) throws Exception {
24         Socket s = new Socket(InetAddress.getLocalHost(),4321);
25         OutputStream out = s.getOutputStream();
26         out.write("服务端,你好".getBytes());
27         InputStream in = s.getInputStream();
28         byte[] buf = new byte[1024];
29         int len = in.read(buf);
30         System.out.println(new String(buf,0,len));
31     }
32 }
33 
34 
35 package com.yyq;
36 
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.OutputStream;
40 import java.net.ServerSocket;
41 import java.net.Socket;
42 
43 public class TcpServer2 {
44     public static void main(String[] args) throws Exception {
45         ServerSocket ss = new ServerSocket(4321);
46         Socket s = ss.accept();
47         InputStream in = s.getInputStream();
48         byte[] buf = new byte[1024];
49         int len = in.read(buf);
50         System.out.println("ip:"+s.getInetAddress().getHostAddress());
51         System.out.println(new String(buf,0,len));
52         OutputStream out = s.getOutputStream();
53         Thread.sleep(10000);
54         out.write("你也好".getBytes());
55     }
56 }    

 

posted @ 2016-01-19 19:52  HuberyQian  阅读(359)  评论(0编辑  收藏  举报