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(); } } } |
原文地址:http://www.cnblogs.com/daifei/p/3718932.html