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 }
posted on 2012-11-21 10:17  ocr  阅读(3061)  评论(0编辑  收藏  举报