服务器端:代码展示
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888); //创建服务器端口号
ExecutorService service = Executors.newCachedThreadPool(); //创建线程池
ConcurrentHashMap<Socket, SocketAddress> hashMap = new ConcurrentHashMap<>();
System.out.println("等待服务器连接。。。");
while (true) {
Socket accept = ss.accept();
hashMap.put(accept, accept.getRemoteSocketAddress());//等待客户端连接
service.submit(() -> { //把所要执行的代码放到线程池中执行
try {
byte[] bytes = new byte[1024]; //创建字节数组
InputStream inputStream = accept.getInputStream();//服务器读入客户端所传来的信息
SocketAddress address = accept.getRemoteSocketAddress();
while (true) {
int read = inputStream.read(bytes); //把读入的信息放到字节数组中
if (read == -1) { //如果读到-1则结束读的过程
break;
}
String s = address + "" + new String(bytes, 0, read); //把读入字节数组的信息转化成字符串并且打印出来
//System.out.println(s);
for (Socket sd : hashMap.keySet()) {
OutputStream outputStream = sd.getOutputStream();
outputStream.write(s.getBytes());
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
}
客户端:代码展示:
public class Demo {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888); //创建客户端
Scanner sc = new Scanner(System.in); //创建输入流
new Thread(() -> {
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
byte[] bytes = new byte[1024];
int read = 0;
try {
read = inputStream.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
if (read == -1) {
break;
}
String string = new String(bytes, 0, read);
System.out.println(string);
}
}).start();
while (true) {
String s = sc.nextLine(); //从控制台输入,并且发送给服务器端
socket.getOutputStream().write(s.getBytes());
}
}
}