2018-8-16初具雏形的聊天室_Java
新建 模板 小书匠
Server服务器端
java 54行
//要支持多个客户端连接, 要记录所有的客户端socket,并给客户端socket发送信息
package westos.org.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server3 {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9527);//创建端口,并设置端口号
System.out.println("等待客户端链接..");
ExecutorService threadPool = Executors.newCachedThreadPool();//创建线程池,应对多个客户端
//一起连接服务器端的情况
ConcurrentHashMap<Socket, SocketAddress> map = new ConcurrentHashMap<>();//创建集合,保存信息
// int i=0;
while (true) {
Socket ac = ss.accept();// 每连接一个新的用户调用一次accept
// i++;
// System.out.println("有"+i+"个客户端已连接..");
map.put(ac, ac.getRemoteSocketAddress());// 将客户socket存入map
// 让线程池中的线程来处理这次请求
threadPool.submit(() -> {
try {
InputStream is = ac.getInputStream();
SocketAddress address = ac.getRemoteSocketAddress();//获得客户端地址
byte[] bytes = new byte[1024];
while (true) {
int len = is.read(bytes);
if (len == -1) {
break;
}
String content = address + " " + new String(bytes, 0, len);// 获取某个客户端发过来的消息内容
for (Socket socket : map.keySet()) {// 向客户端socket写入消息内容
OutputStream os = socket.getOutputStream();
os.write(content.getBytes());
}
}
// System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
}
Client 客户端
java 43行
package westos.org.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client3 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 9527);//连接自己电脑时专用IP它的别名 localhost
// System.out.println("请给自己起一个昵称:");
// Scanner sc1 = new Scanner(System.in);
// String name = sc1.nextLine();
new Thread(() -> {
try {
InputStream is = socket.getInputStream();
while (true) {
byte[] buf = new byte[1024];
int len = is.read(buf);
if (len == -1) {
break;
}
System.out.println(new String (buf,0,len));}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
Scanner sc = new Scanner(System.in);
while (true) {// 从控制台反复读入内容
String content = sc.nextLine();
OutputStream os = socket.getOutputStream();
os.write(content.getBytes());
}
}
}