服务端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
public class Server {
private ServerSocket socket;
private Integer port;
private List<Socket> socketList;
private ArrayBlockingQueue<String> queue;
public Server(Integer port) throws IOException {
this.port = port;
socket = new ServerSocket(port);
socketList = Collections.synchronizedList(new ArrayList<>());
queue = new ArrayBlockingQueue<>(100);
}
private void openNewServerThread(Socket st){
new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(st.getInputStream()));
while (!socket.isClosed()){
String s = br.readLine();
if (s.equalsIgnoreCase("quit")){
socket.close();
break;
}
queue.add(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void run() throws InterruptedException, IOException {
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Socket accept = socket.accept();
System.out.println("新连接");
socketList.add(accept);
openNewServerThread(accept);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
while (true){
String s = queue.take();
System.out.println("服务器接受到信息:" + s);
for (Socket ts : socketList) {
if (ts.isClosed()){
socketList.remove(ts);
continue;
}
try {
PrintStream ps = new PrintStream(ts.getOutputStream());
ps.println(s);
ps.flush();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException, InterruptedException {
new Server(8969).run();
}
}
客户端
package test;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private Socket socket;
private String ip;
private Integer port;
private String clientName;
PrintStream ps;
BufferedReader br;
public Client(String clientName, String ip, Integer port) throws IOException {
this.ip = ip;
this.port = port;
this.clientName = clientName;
socket = new Socket(ip, port);
ps = new PrintStream(socket.getOutputStream());
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public void sendMsg(String msg) {
ps.println(clientName + ":" + msg);
ps.flush();
}
public void onReceive(){
new Thread(new Runnable() {
@Override
public void run() {
try {
while (!socket.isClosed()) {
String s = br.readLine();
System.out.println("onReceive:" + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void close() throws IOException {
br.close();
ps.close();
socket.close();
}
public void run() throws IOException {
onReceive();
Scanner sc = new Scanner(System.in);
while (true){
String s = sc.nextLine();
sendMsg(s);
if ("quit".equalsIgnoreCase(s)){
break;
}
}
close();
}
public static void main(String[] args) throws IOException {
new Client("user1", "127.0.0.1", 8969).run();
}
}