java基于线程和网络编程的Tcp聊天室
客户端代码
public class Client {
public static void main(String[] args) {
try {
Socket socket=new Socket("127.0.0.1",10086);
new Thread(new ReadThread(socket)).start();
new Thread(new WriterThread(socket)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端代码
public class Server {
public static CopyOnWriteArrayList<Socket>sockets=new CopyOnWriteArrayList<>();
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(5, 20);
try (ServerSocket serverSocket = new ServerSocket(10086)) {
while (true){
Socket accept = serverSocket.accept();
pool.execute(new ServerThread(accept));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
读操作线程
public class ReadThread implements Runnable{
private Socket socket;
public ReadThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))){
String str;
while ((str=reader.readLine())!=null){
System.out.println(str);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
写操作线程
public class WriterThread implements Runnable{
private Socket socket;
public WriterThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
Scanner sc=new Scanner(System.in)){
String str;
while (true){
str=sc.nextLine();
if (str.equals("exit")){
System.exit(0);
}
printWriter.println(str);
printWriter.flush();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
自定义线程池
public class ThreadPool {
private ExecutorService pool;
public ThreadPool(int max,int dequeMax) {
pool=new ThreadPoolExecutor(5,max,1, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(dequeMax),new DiscardOldestPolicy());
}
public void execute(Runnable runnable){
pool.submit(runnable);
}
}
服务器端线程操作
public class ServerThread implements Runnable{
private Socket socket;
private PrintWriter printWriter;
private BufferedReader reader;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
String name = socket.getRemoteSocketAddress().toString();
System.out.println(name+":已上线");
printAll(name,"已上线");
try {
reader= new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str=reader.readLine())!=null){
if (str.equals("exit")){
Server.sockets.remove(socket);
printAll(name,"已下线");
break;
}else {
printAll(name,str);
}
}
} catch (IOException e) {
System.out.println(socket.getRemoteSocketAddress()+"已下线");
}
}
public void printAll(String name,String str){
for (Socket socket1 : Server.sockets) {
if (socket1!=socket){
try {
printWriter=new PrintWriter(socket1.getOutputStream());
printWriter.println(name+":"+str);
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.sockets.add(socket);
}
}
|