- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在制作一个聊天室项目,其中服务器接受许多客户端,并且客户端写入的任何内容都会到达其他客户端等等。不幸的是,服务器最多接受 2 个客户端,并且在一个客户端写入输入后它会出错。
public class Server2 {
private static ArrayList<Socket> clients;
private ServerSocket server;
DataOutputStream os;
DataInputStream in;
Socket s;
public Server2() throws IOException {
server = new ServerSocket(5000);
clients = new ArrayList<Socket>();
System.out.println("Waiting for connections...");
runOutput();
}
public void addClient() throws IOException {
s = server.accept();
clients.add(s);
System.out.println("A new Client has joined");
}
public void runOutput() {
Thread n = new Thread(new Runnable() {
public void run() {
try {
addClient();
} catch (IOException e) {
e.printStackTrace();
}
}
});
n.start();
Thread input = new Thread(new Runnable() {
public void run() {
try {
addClient();
in = new DataInputStream(s.getInputStream());
os = new DataOutputStream(s.getOutputStream());
String st = in.readLine();
System.out.println(st);
os.writeBytes(st);
for(int i = 0; i < clients.size(); i++)
{
DataOutputStream oo = new DataOutputStream(clients.get(i).getOutputStream());
oo.writeBytes(st);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
input.start();
}
public static void main(String[] args) throws IOException {
Server2 server = new Server2();
}
}
和客户端类:
public class Client2 {
final public static String host = "localhost";
final public static int port = 5000;
Socket socket;
DataInputStream in;
DataOutputStream ou;
Scanner chat;
boolean run;
String name;
public Client2(String n) throws IOException {
name = n ;
socket = new Socket(host , port);
System.out.println("Connection Successful");
run = true;
runOutput();
}
public void runOutput() {
Thread input = new Thread(new Runnable() {
public void run() {
while (run) {
try {
in = new DataInputStream(socket.getInputStream());
String s = in.readLine();
System.out.println(s);
if(chat.nextLine().compareTo("QUIT") == 0)
run = false;
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
input.start();
Thread t = new Thread(new Runnable() {
public void run() {
while (run) {
try {
ou = new DataOutputStream(socket.getOutputStream());
chat = new Scanner(System.in);
ou.writeBytes(name + " says :" + chat.nextLine() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
public static void main(String[] args) throws IOException {
Client2 client = new Client2("Ahmed");
}
}
最佳答案
您的“n”线程没有循环,这意味着它会运行一次(接受连接),然后结束。
Thread n = new Thread(new Runnable() {
public void run() {
while(true) { //control this with your own boolean, or it will run forever
try {
addClient();
}catch(IOException e) { }
}
}
});
别担心,您的线程将在“ss.accept()”处暂停,因为它会等到套接字被接受后才能继续。
Thread thread = new Thread(new Runnable() {
public void run() {
while(running) {
String input;
while((input = inputstream.readUTF()) != null) {
//handle input
}
}
}
});
抱歉,写得太快了,没有太多时间。如果它没有帮助,我会回来并将它与您的代码联系起来。
您需要某种方式从服务器的输入流中持续检索输入,然后您可以在其中处理输入。
每次您从 inputstream.readUTF() 检索内容时,该循环都会循环(当然,它不是空的)。希望这个例子对你有帮助
在实际阅读您的代码并对其进行测试后,我注意到您的结构似乎有点不对劲。首先,服务器中的 Thread n
负责接受连接 (addClient()
),但您也首先在 Thread input
中调用它>?
Thread n
正在处理接受连接,因此对于循环,Thread n
没问题。Thread input
正在处理从客户端检索到的输入。这就是您感到困惑的地方。
每个客户端都应该有自己的 InputStream 和 OutputStream 服务器端。类似于您拥有套接字列表的方式(因为您将在服务器端创建多个套接字),您也需要多个流。为此,我建议创建一个 User 类,然后如果有的话,为 User 使用 ArrayList,而不是 Socket。
public class User extends Thread { //create a Thread for each connection to handle data seperately
DataInputStream in;
DataInputStream out;
Socket socket;
public User(Socket socket) { //creates a stream for the socket that the user connected with
this.socket = socket;
initStream();
}
public void initStream() { //inits streams after socket is initiated (through ss.accept())
try {
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
}catch(IOException e) { e.printStackTrace(); }
}
public void closeStream() throws IOException { //throws exception since i have a chance to catch it in my run() method
out.close(); in.close();
socket.close();
}
public void sendMessage(String string) {
try {
out.writeUTF(string);
}catch(IOException e) { e.printStackTrace(); }
}
public void run() { //when thread starts, accept/handle data
String input;
try {
while((input = in.readUTF()) != null) {
//handle input
}
closeStream();
}catch(IOException e) { e.printStackTrace(); }
}
}
in.readLine()
已贬值,这意味着它已过时且不应使用(以避免错误)。现在您已经设置了处理数据的用户类,现在您可以在每次收到连接时创建一个新用户。
public class Server {
private static boolean running = true;
public static ArrayList<User> userlist;
public static synchronized void stop() { //synchronized in-case another thread other than the main thread stops the server
if(!running) return;
running = false;
}
public static void main(String[] args) {
/* uses the JVM thread (main thread for applications), so if you dont wanna
** dedicate your entire server to accepting connections only (since Users are in new thread)
** create a new thread for the code in this void method. */
try {
ServerSocket ss = new ServerSocket(8000);
userlist = new ArrayList<User>();
User user; //holds the user so we can put it in the list, then start
while(running) {
user = new User(ss.accept());
list.add(user);
user.start();
}
} catch(IOException e) {
e.printStackTrace(); }
}
}
希望这能让您更好地了解服务器的运行方式。
至于你的客户..好吧,你应该意识到很多事情:
首先,大问题,您在每个循环中重新初始化 DataOutputStream,这将导致流服务器端关闭。必须将其从循环中取出,可能将其放在之前(或者查看我的服务器示例以获得处理流初始化的更好想法)。
其次,名称应该保存在服务器上,而不是客户端上。这样,很容易遍历名称,检查它是否被占用,等等。
第三,与网络无关,但看到你如何从不引用 Thread n
或 Thread input
,除了启动它,你应该删除引用变量。 (尽管我很确定本地变量已被垃圾收集器收集,但看起来仍然更好)。示例:
public void method() {
new Thread(new Runnable() {
public void run() {
//code
}
}).start();
new Thread(new Runnable() {
//run method
}).start();
}
希望这有助于您了解多线程服务器的工作原理! :)
PS:这是一个非常基本的服务器,真的不应该用于大型应用程序。 创建新线程 (new User()) 会导致大量开销,因此最好使用 ExecutorService 或其他类型的线程池服务来处理连接。祝你好运!
关于java - Java中的服务器客户端聊天室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807941/
我想在一些计算机之间建立点对点连接,这样用户就可以在没有外部服务器的情况下聊天和交换文件。我的第一个想法如下: 我在服务器上创建了一个中央 ServerSocket,所有应用程序都可以连接到该服务器。
我正在 Unity 中构建多人游戏。为此,我必须将一些值从客户端发送到两个或多个通过服务器连接的客户端。我想将其构建为服务器真实游戏。客户端将使用 Android,他们的数据将通过服务器同步(可能是一
练习 C 网络编程:我正在编写一个简单的 TCP 客户端-服务器应用程序,它应该将消息(在每个客户端的单独线程中)作为字符串从服务器发送到客户端并在客户端(稍后将成为控制台商店应用程序)。我首先发送消
我使用证书身份验证设置了 AWS Client VPN。我正在为客户端-客户端访问系统进行设置,基本上如 this AWS scenario/example 中所述.一切正常,如果我知道他们的 IP
我正在开发一个小型客户端1/客户端2、服务器(线程)TCP 游戏。在尝试处理延迟问题时,我意识到我的 transmitState() 中存在缺陷。它强制将不必要的信息传递到通讯流中,从而造成迟缓,将汽
来自文档:Configurable token lifetimes in Azure Active Directory (Public Preview) 它提到“ secret 客户端”,刷新 tok
Apollo 客户端开发工具无法连接到我的应用程序。我已在 ApolloClient 构造函数中将 connectToDevTools 传递为 true,但没有任何 react 。我也试过this p
我想在 Pod 内使用 Fabric8 kubernetes 客户端 (java)。如何获取部署集群的 kubernetes 客户端? 我可以使用该集群的 kubeconfig 文件获取任何集群的配置
我正在阅读 the security issue with Log4j我了解此产品受此漏洞影响。但是 Oracle 客户端 11.2 和 12 是否受此问题影响? 我找不到这些产品是否使用任何 Log
Eureka 服务器设置 pom.xml 1.8 Hoxton.SR1 org.springframework.cloud spring
我有一个点对点(客户端/服务器)设置(通过本地 LAN),它使用 Netty,一个 Java 网络框架。我使用原始 TCP/IP(例如,没有 HTTP)进行通信和传输。现在,根据要求,我们希望转向 T
上一篇已经实现了ModbusTcp服务器和8个主要的功能码,只是还没有实现错误处理功能。 但是在测试客户端时却发现了上一篇的一个错误,那就是写数据成功,服务器不需要响应。 接下来要做的就是实现Modb
有没有办法将二维十六进制代码数组转换为 png 图像? 数组看起来像这样(只是更大) [ [ '#FF0000', '#00FF00' ], [ '#0000FF'
我是套接字编程的新手。每次我运行客户端程序时,它都会说“无法连接到服务器”。谁能告诉我我在哪里犯了错误。任何帮助将不胜感激。 这是client.c #include #include #inclu
我们在UNIX环境下制作了简单的client.c和server.c程序。我们使用它来传输一个简单的文本文件,首先打开它,然后读取它并使用 open、read 和 send 系统调用发送;在客户端,我接
当我的程序来自 my previous question正在响应客户端,它应该发送加密消息。 当客户端连接时,它会发送一条类似“YourMessage”的消息。现在我想做的是,当客户端连接时,应该以某
我正在使用 C 和 putty 编写客户端/服务器程序。两个 c 文件位于同一系统上。 我目前在向客户端写回其正在使用的框架以及打印我的框架时遇到问题。它打印出 3 0 9 8,但随后开始打印 134
我正在使用 C 中的 select() 制作一个模拟快餐或其他任何东西的客户端服务器。 我有客户随机点 1-5 种“食物”。服务器每 30 秒决定一次。所有客户最喜欢的食物是什么?他为那些客户提供服务
对于单机游戏,基本的游戏循环是(来源:维基百科) while( user doesn't exit ) check for user input run AI move enemies
1、CentOS安装TortoiseSVN 复制代码 代码如下: yum install -y subversion 2、SVN客户端命令
我是一名优秀的程序员,十分优秀!