上一篇介绍Socket基本用法的文章:
https://www.jianshu.com/p/58f3068d26d8
使用Socket来搭建一个cmd的简易聊天窗口:
实现效果:
1.PNG
需要的类有:
1、监听客户端连接线程
2、客户端类
3、客户端管理类
主方法:
public static void main(String[] args) throws IOException {
//开启一个接收连接的子线程
Thread thread = new Thread(new MyThread());
thread.start();
}
监听客户端连接的线程类:
static class MyThread implements Runnable {
//服务端
ServerSocket server = new ServerSocket(8000);
MyThread() throws IOException {
}
@Override
public void run() {
while (true){
//客户端
try {
Socket client = server.accept();
//添加客户端
SocketClient socketClient = new SocketClient(client);
socketClient.start(); //开始运行客户端
ClientManage.getInstance().add(socketClient);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//客户端,继承Thread类,每一个聊天窗口都用一个线程执行
static class SocketClient extends Thread {
private Socket client;
private PrintStream print; //打印流
private BufferedReader br;
private boolean flag = true;
//初始化
public SocketClient(Socket client) throws IOException {
this.client = client;
//客户端输出流
print = new PrintStream(client.getOutputStream());
print.write(getString("连接成功啦!"));
print.println();
br = new BufferedReader(new InputStreamReader(client.getInputStream(),"GBK"));
}
//关闭客户端
private void closeClient() throws IOException {
br.close();
print.close();
client.close();
}
@Override
public void run() {
while (flag){
String str;
try {
str = br.readLine();
if ("exit".equalsIgnoreCase(str)){
flag = false;
print.println();
print.write(getString("退出连接!"));
ClientManage.chatPrint(this,"退出了群聊!");
closeClient(); //关闭客户端
}else {
print.write(getString("你输入了:" + str));
print.println();
//聊天室,群发消息给各个线程
if (str!=null){
ClientManage.chatPrint(this,str);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//输出
public void out(String str,String name) throws IOException {
print.write(getString(name + "输入了:" + str));
print.println();
}
//格式转换,不然输出乱码
private static byte[] getString(String str) throws UnsupportedEncodingException {
return str.getBytes("GBK");
}
}
//客户端管理类
static class ClientManage{
private static Vector<SocketClient> clientList = new Vector<>();
public ClientManage(){
}
//遍历输出聊天消息,实现群聊功能
public static void chatPrint(SocketClient socketClient,String str) throws IOException {
for (SocketClient vector : clientList){
if (!vector.equals(socketClient)){
vector.out(str,socketClient.getName());
}
}
}
public static Vector<SocketClient> getInstance(){
return clientList;
}
}
网友评论