JavaSocket编程的一个简单例子

 1 // 客户端程序
 2 import java.io.*;
 3 import java.net.ServerSocket;
 4 import java.net.Socket;
 5 
 6 public class user{
 7     public static void main(String[] args) throws InterruptedException {
 8         String s = null;
 9         Socket mysocket;
10         DataOutputStream out = null;
11         DataInputStream in = null;
12         int i =1;
13         try {
14             mysocket= new Socket("localhost",4331);
15             in = new DataInputStream(mysocket.getInputStream());
16             out = new DataOutputStream(mysocket.getOutputStream());
17             out.writeInt(i);
18             while(true){
19                  i = (i+1)%128;
20                  s = in.readUTF();
21                  out.writeInt(i);
22                  System.out.println("客户收到:"+s);
23                  Thread.sleep(500);
24             }
25         }catch(IOException e) {
26             
27         }
28     }
29 }
 1 //服务器端程序
 2 import java.io.*;
 3 import java.net.ServerSocket;
 4 import java.net.Socket;
 5 
 6 public class Test2{
 7     public static void main(String[] args){
 8         ServerSocket server = null;
 9         Socket you = null;
10         DataOutputStream out = null;
11         DataInputStream in = null;
12         
13         try{
14             server = new ServerSocket(4331);
15             
16         }catch(IOException e1){}
17         
18         try{
19             you = server.accept();
20             in = new DataInputStream(you.getInputStream());
21             out = new DataOutputStream(you.getOutputStream());
22             while(true)
23             {
24                 int m = 0;
25                 m = in.readInt();
26                 out.writeUTF("你说的对应数字为:" + (char)m);
27             }
28         }catch(IOException e2) { }
29         
30     //    catch(InterruptedException e) { }
31             
32         
33     }
34 }

转载于:https://www.cnblogs.com/persistences/archive/2012/11/21/2780233.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值