java Socket多线程需要我们不断的学习,在学习的时候我们就会发现在服务器的配置上有不少的问题。下面我们就来看看服务器源代码是如何编写的,以便大家更好的使用jav
va Socket多线程。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.ServerSocket;
import java.Socket;
import java.util.ArrayList;
import java.util.List;
import urrent.ExecutorService;
import urrent.Executors;
public class ChatServer {
private static final int PORT = 1234; // 端口号
private static List<Socket> list = new ArrayList<Socket>(); // 保存连接对象
private ExecutorService exec;
private ServerSocket server;
public static void main(String[] args) {
new ChatServer();
}
public ChatServer() {
try {
server = new ServerSocket(PORT);
exec = wCachedThreadPool();
System.out.println(“服务器已启动!”);
Socket client = null;
while (true) {
client = server.accept(); // 接收客户连接
list.add(client);
ute(new ChatTask(client));
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class ChatTask implements Runnable {
private Socket socket;
private BufferedReader br;
private PrintWriter pw;
private String msg;
public ChatTask(Socket socket) throws IOException {
this.socket = socket;
br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
msg = “【” + InetAddress() + “】进入聊天室!当前聊天室有【”
+ list.size() + “】人”;
sendMessage();
}
public void run() {
try {
while ((msg = br.readLine()) != null) {
if (im().equals(“bye”)) {
ve(socket);
br.close();
pw.close();
msg = “【” + InetAddress() + “】离开聊天室!当前聊天室有【”
+ list.size() + “】人”;
socket.close();
sendMessage();
break;
} else {
msg = “【” + InetAddress() + “】说:” + msg;
sendMessage();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发消息给聊天室的所有人
*/
private void sendMessage() throws IOException {
System.out.println(msg);
for (Socket client : list) {
pw = new OutputStream(), true);
pw.println(msg);
}
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
公司介绍源码 import java.Socket;
import urrent.ExecutorService;
import urrent.Executors;
public class ChatClient {
private static final int PORT = 7891;
private static ExecutorService exec = wCachedThreadPool();
public static void main(String[] args) throws Exception {
new ChatClient();
}
public ChatClient() {
try {
Socket socket = new Socket(“221.130.165.41″, PORT);
ute(new Sender(socket));
System.out.println(“【” + InetAddress() + “】您好,欢迎来到简易聊天室!”);
BufferedReader br = new BufferedReader(new InputStream()
)));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println(“收到—->”+msg);
}
} catch (Exception e) {
}
}
以上就是对java Socket多线程的相关介绍。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论