首页 > 其他 > 详细

socket编程2

时间:2014-05-09 19:45:04      阅读:336      评论:0      收藏:0      [点我收藏+]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package tcp;
 
import java.io.BufferedReader;
 
import java.io.BufferedWriter;
 
import java.io.IOException;
 
import java.io.InputStreamReader;
 
import java.io.OutputStreamWriter;
 
import java.io.PrintWriter;
 
import java.net.ServerSocket;
 
import java.net.Socket;
 
public class ServerCode
 
{
    public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(3333);
 
       System.out.println("The Server is start: " + s);
 
              // 阻塞,直到有客户端连接
 
       Socket socket = s.accept();
 
       try {
           System.out.println("Accept the Client: " + socket);                  
 
          //设置IO句柄
          BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 
          PrintWriter out = new PrintWriter(new BufferedWriter(
 
          new OutputStreamWriter(socket.getOutputStream())), true);                   
 
          while (true)
          {
              String str = in.readLine();
              if (str.equals("byebye")){break;}
              System.out.println("In Server reveived the info: " + str);
              out.println(str);
              }
          }
       finally {
           System.out.println("close the Server socket and the io.");
           socket.close();
           s.close();
           }
 
    }
 
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package tcp;
import java.io.BufferedReader;
 
import java.io.BufferedWriter;
 
import java.io.IOException;
 
import java.io.InputStreamReader;
 
import java.io.OutputStreamWriter;
 
import java.io.PrintWriter;
 
import java.net.InetAddress;
 
import java.net.Socket;
public class ClientCode
 
{
    public static void main(String[] args) throws IOException{
        Socket socket = new Socket("localhost", 3333);
        try{
             
         System.out.println("socket = " + socket);
         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 
          PrintWriter out = new PrintWriter(new BufferedWriter(
 
          new OutputStreamWriter(socket.getOutputStream())), true);
 
          out.println("Hello Server,I am ");
 
           String str = in.readLine();
           System.out.println(str);
           out.println("byebye");
           }
             finally {
                 System.out.println("close the Client socket and the io.");
                 socket.close();
 
       }
      }
 
}

  

socket编程2,布布扣,bubuko.com

socket编程2

原文:http://www.cnblogs.com/daifei/p/3718932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!