java简易多用户聊天室
作者:网络转载 发布时间:[ 2016/9/7 13:22:13 ] 推荐标签:测试开发技术 Java
java Swing写的一个小Demo
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Server {
static Boolean start = true;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new Server().start();
}
public void start() {
Socket s = null;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
while (start) {
s = serverSocket.accept();
Client client = new Client(s);
new Thread(client).start();
clients.add(client);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Client implements Runnable {
private Socket socket;
private BufferedReader br;
private PrintWriter pWriter;
private String mes;
public Client(Socket socket) {
this.socket = socket;
try {
this.br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
this.pWriter = new PrintWriter(socket.getOutputStream(),true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try{
while (start) {
while((mes=br.readLine())!=null){
System.out.println(mes);
for (int i = 0; i < clients.size(); i++) {
if(!this.equals(clients.get(i)))
clients.get(i).pWriter.println(mes);
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if (br!=null) {
br.close();
}
if(socket!=null){
socket.close();
}
if(this!=null){
clients.remove(this);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11