Java网络编程(TCP协议-服务端和客户端交互)

客户端:

 1 package WebProgramingDemo;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.Socket;
 7 import java.net.UnknownHostException;
 8 
 9 public class SocketDemo {
10 
11     /**
12      * @param args
13      * @throws IOException 
14      * @throws UnknownHostException 
15      */
16     public static void main(String[] args) throws  IOException {
17 
18         Socket s=new Socket("192.168.2.103",10002);
19         OutputStream out=s.getOutputStream();
20         out.write("Java".getBytes());
21         InputStream is=s.getInputStream();
22         byte buf[]=new byte[1024];
23         int len=is.read(buf);
24         System.out.println(new String(buf,0,len));
25         s.close();
26     }
27 
28 }

服务端:

 1 package WebProgramingDemo;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 public class ServerSocketDemo {
10 
11     /**
12      * @param args
13      * @throws IOException
14      */
15     public static void main(String[] args) throws IOException {
16 
17         ServerSocket ss = new ServerSocket(10002);
18         Socket s = ss.accept();
19         String ip = s.getInetAddress().getHostAddress();
20         System.out.println(ip + "....connected....");
21         InputStream in = s.getInputStream();
22         int len = 0;
23         byte[] buf = new byte[1024];
24         len = in.read(buf);
25         System.out.println(new String(buf, 0, len));
26         OutputStream os=s.getOutputStream();
27         os.write("收到".getBytes());
28         os.close();
29         s.close();
30         ss.close();
31     }
32 
33 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值