基于TCP的多人聊天室(一)

基于TCP的多人聊天室(一)

利用TCP来实现网络多人聊天室,此版本只能实现发送接收,不能随意发言,还没实现客户端互相传输,只能自己发送自己接收。

聊天室服务器:

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
/**
* 聊天室服务器
*
*/
public class Chat_Server {
public static void main(String[] args) throws IOException {
System.out.println("-------Server-------");
// 1.指定端口,使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(6666);
// 2.阻塞式等待链接 accept
while (true) {
Socket Server = server.accept();
System.out.println("客户端连接已建立");
new Thread(() -> {
DataInputStream dis = null;
DataOutputStream dos = null;
try {
dis = new DataInputStream(Server.getInputStream());
dos = new DataOutputStream(Server.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
boolean flag = true;
// 3.操作:输入输出流
try {
while (flag) {
dos.writeUTF(dis.readUTF());
dos.flush();
}
} catch (IOException e) {
flag=false;
}
// 4.释放资源
{
try {
if (null == dis)
dis.close();
if (null == dis) {
dos.close();
}
if (null == dis) {
Server.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}).start();
}
}
}

聊天室客户端:

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
/**
* 聊天室客户端
*
*/
public class Chat_Client {

public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("-------Client-------");
// 1.建立连接:使用Socket创建客户端:服务器地址和端口
Socket Client = new Socket("localhost", 6666);
// 2.操作:输入输出流
DataOutputStream dos = new DataOutputStream(Client.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
DataInputStream dis = new DataInputStream(Client.getInputStream());
boolean flag = true;
while (flag) {
String st = bf.readLine();
dos.writeUTF(st);
dos.flush();
String sss = dis.readUTF();
System.out.println(sss);
}
// 释放资源
dis.close();
dos.close();
Client.close();

}
}
原创技术分享,您的支持将鼓励我继续创作
0%