# 1.创建任务对象
~~~
import java.io.*;
import java.net.Socket;
/**
* 任务对象
*/
public class ServerRunnableTarget extends Thread {
private Socket socket;
public ServerRunnableTarget(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
//1. 从socket中获取字节输入流对象
//把字节输入流包装成缓存字节输入流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg=bufferedReader.readLine())!=null){
// 2.把服务器接收到的消息推送给所有在线的socket
sendMsgToAllClient(msg);
}
} catch (Exception e) {
// 下线
System.out.println("有人下线了");
// 删除下线的
Server.allSocketOnLien.remove(socket);
}
}
/**
* 把服务器接收到的消息推送给所有在线的socket
* @param msg
*/
private void sendMsgToAllClient(String msg) throws IOException {
for (Socket socket1 : Server.allSocketOnLien) {
PrintStream stream = new PrintStream(socket1.getOutputStream());
stream.println(msg);
stream.flush();
}
}
}
~~~
# 2.创建服务端
~~~
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* 1.注册端口
* 2.接收客户端的消息连接,交给独立的线程来处理
* 3.把当前连接的socket缓存到一个集和列表中
* 4.接收socket的消息,然后推送给当前所以在线的socket接收
*/
public class Server {
//
public static final List<Socket> allSocketOnLien =new ArrayList<Socket>();
public static void main(String[] args) {
System.out.println("服务端启动");
try {
// ServerSocket 对象进行服务器端口注册
ServerSocket serverSocket = new ServerSocket(9999);
while (true){
Socket socket = serverSocket.accept();
// 把在线socket存入一个在线集合中
allSocketOnLien.add(socket);
// 为当前socket分配一个独立的线程来与之处理
new ServerRunnableTarget(socket).start();
}
}catch (Exception e){
e.fillInStackTrace();
}
}
}
~~~
# 3.客户端
~~~
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
// 创建socket链接请求
Socket socket = new Socket("127.0.0.1", 9999);
// 从socket中获取字节输出流对象
OutputStream socketOutputStream = socket.getOutputStream();
//把字节输出流包装成打印流
PrintStream printStream = new PrintStream(socketOutputStream);
// 接收信息
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 扫描器
Scanner scanner = new Scanner(System.in);
// 打印信息线程
Thread thread = new Thread(){
@Override
public void run() {
while (true){
try {
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
thread.start();
// 发送信息
while (true) {
System.out.println("请说:");
printStream.println(scanner.nextLine());
printStream.flush();
}
} catch (Exception e) {
e.fillInStackTrace();
}
}
}
~~~