1.服务器端
1.1 服务器启动入口:
package com.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServer {
public static ArrayList<Socket> socketList = new ArrayList<Socket>();
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(30000);
while (true) {
System.out.println("等待客户端的访问... ...");
Socket socket = serverSocket.accept();
socketList.add(socket);
new Thread(new ServerThread(socket)).start();
}
}
}
1.2 服务器线程:
package com.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class ServerThread implements Runnable {
Socket socket = null;
BufferedReader bufferedReader = null;
public ServerThread(Socket socket) throws IOException {
this.socket = socket;
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
@Override
public void run() {
String content = null;
try {
while((content = readFromClient()) != null){
for (Socket socket:MainServer.socketList) {
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println("来自客户端:"+content);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFromClient(){
try {
return bufferedReader.readLine();
} catch (IOException e) {
MainServer.socketList.remove(socket);
}
return null;
}
}
2.客户端
2.1 客户端主入口:
package com.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket clientSocket = new Socket("127.0.0.1", 30000);
PrintStream printStream = new PrintStream(clientSocket.getOutputStream());
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while ((line = bufferedReader.readLine()) != null) {
printStream.println(line);
}
}
}
2.2 客户端线程:
package com.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClientThread implements Runnable {
private Socket socket;
BufferedReader bufferedReader = null;
public ClientThread(Socket socket) throws IOException{
this.socket = socket;
bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
}
@Override
public void run() {
String conString = null;
try {
while ((conString = bufferedReader.readLine()) != null) {
System.out.println("来自服务器的广播:"+conString);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}