标签:style http color io os ar java 数据 sp
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
|
packagecom.gufengxiachen.sthreadchatapp;
/**
*
@author GUXIA
*/
importjava.io.BufferedReader;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.ServerSocket;
importjava.net.Socket;
publicclassChatServer {
publicstaticvoidmain(String[] args) {
try{
//创建服务器端套接字,接受来自客户端的连接请求
ServerSocket ss=newServerSocket(9999);
Socket s=ss.accept();
//获取客户端套接字的输出流
OutputStream os=s.getOutputStream();
DataOutputStream dos=newDataOutputStream(os);
//获取客户端输入流
InputStream is=s.getInputStream();
DataInputStream dis=newDataInputStream(is);
//创建字符输入流接受键盘输入
InputStreamReader isr=newInputStreamReader(System.in);
BufferedReader br=newBufferedReader(isr);
String message;
while(true){
//获取客户端输入流,并打印在屏幕上,如果客户端说的是“再见”,退出
message=dis.readUTF();
System.out.println("客户端:"+message);
if(message.equals("再见"))
break;
//读取键盘输入并写入到输出流(客户端的输入流)
message=br.readLine();
dos.writeUTF(message);
}
dis.close();
dos.close();
ss.close();
s.close();
}catch(Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
|
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
|
packagecom.gufengxiachen.sthreadchatapp;
/**
*
@author GUXIA
*/
importjava.io.BufferedReader;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.Socket;
publicclassChatClient {
publicstaticvoidmain(String[] args) {
try{
//创建客户端套接字
Socket sc=newSocket("localhost",9999);
//获取套接字输入流
InputStream is=sc.getInputStream();
DataInputStream dis=newDataInputStream(is);
//获取套接字输出流
OutputStream os=sc.getOutputStream();
DataOutputStream dos=newDataOutputStream(os);
//创建字符输入流接受键盘输入
InputStreamReader isr=newInputStreamReader(System.in);
BufferedReader br=newBufferedReader(isr);
//聊天
String message;
while(true){
//读取键盘输入的字符,写到客户端输出流
message=br.readLine();
dos.writeUTF(message);
if(message.equals("再见"))
break;
//读取服务器端的数据并打印到屏幕上
message=dis.readUTF();
System.out.println("服务器:"+message);
}
dis.close();
dos.close();
sc.close();
}catch(Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
|
标签:style http color io os ar java 数据 sp
原文地址:http://my.oschina.net/bv10000/blog/325137