gpt4 book ai didi

java - 多线程客户端-服务器聊天,使用套接字

转载 作者:行者123 更新时间:2023-12-02 07:45:20 25 4
gpt4 key购买 nike

服务器和客户端使用我自己的协议(protocol)进行通信,该协议(protocol)看起来像 XMPP。我应该实现聊天应用程序。因此,当一个用户写入字符串时,它应该立即通过服务器发送到其他客户端。我在服务器上有方法 sendToAll 。但是用户只有在按下回车键时才能看到其他用户的消息。用户如何在不按回车按钮的情况下接收消息?

这是我的客户:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;

import dataart.practice.protocols.XMLProtocol;

public class Client {
public static final String SERVER_HOST = "localhost";
public static final Integer SERVER_PORT = 4444;
public static final Logger LOG = Logger.getLogger(Client.class);
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader inu;

public static void main(String[] args) throws IOException {

System.out.println("Welcome to Client side");
XMLProtocol protocol = new XMLProtocol();
Socket fromserver = null;

fromserver = new Socket(SERVER_HOST, SERVER_PORT);

in = new BufferedReader(new InputStreamReader(fromserver.getInputStream()));

out = new PrintWriter(fromserver.getOutputStream(), true);

inu = new BufferedReader(new InputStreamReader(System.in));

String fuser, fserver;
while (true){
if(in.ready()){//fserver = in.readLine()) != null) {
System.out.println("asdasdsd");

fuser = inu.readLine();
if (fuser != null) {
if (fuser.equalsIgnoreCase("close"))
break;
if (fuser.equalsIgnoreCase("exit"))
break;

protocol.setComId((long) 0);
protocol.setContent(fuser);
protocol.setLogin("Guest");

try {

JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
jaxbMarshaller.marshal(protocol, out);
out.flush();

} catch (JAXBException e) {
LOG.error("Error while processing protocol" + e);
}
}
}

}

out.close();
in.close();
inu.close();
fromserver.close();
}

}

还有带有 ServerThread 的服务器。

public static void main(String[] args) throws IOException {

LOG.trace("Server started");
ServerSocket s = new ServerSocket(SERVER_PORT);

try {
while (true) {
LOG.trace("Waiting for connections...");
Socket socket = s.accept();
try {
// new ServerThread(socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
userCounter++;
addUser("Guest" + userCounter, out);
LOG.trace("User " + userCounter + " has been added!");
exec.execute(new ServerThread(socket, in, out));

} catch (IOException e) {
socket.close();
}
}
} finally {
s.close();
}
}

服务器线程。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.Socket;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

import dataart.practice.protocols.XMLProtocol;
import dataart.practice.serverUtils.Commands;

public class ServerThread implements Runnable {
private static final Logger LOG = Logger.getLogger(ServerThread.class);

private XMLProtocol protocol;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String buffer = "";// may be exist another. way but it's not working
private Boolean login = false;

public ServerThread(Socket s, BufferedReader in, PrintWriter out) throws IOException {
this.in = in;
this.out = out;
out.println("</XMLProtocol>");
socket = s;
new Thread(this);
}

public void run() {
try {
while (true) {
if ((buffer = in.readLine()) != null) {
if (buffer.endsWith("</XMLProtocol>")) {
protocol = getProtocol(buffer);
//Server.onlineUserList.put(protocol.getLogin(), out);
/* if (!login){
out.println("Maybe login first?");

}
*/
LOG.trace("Getting message from user: " + protocol.getLogin() + " recived message: " + protocol.getContent());
///out.println(protocol.getLogin() + " says:" + protocol.getContent());
Server.sendToAll(protocol.getContent()+"</XMLProtocol>");


} else {
LOG.trace("Nop protocol do not send with it end");
}
}
}
} catch (IOException e) {
LOG.error("Error in reading from stream: " + e);
} catch (JAXBException e) {
LOG.error("Error in Marshalling: " + e);
} finally {
try {
socket.close();
LOG.trace("Socket closed");
} catch (IOException e) {
LOG.error("Socket no closed" + e);
}
}
}

public XMLProtocol getProtocol(String buffer) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (XMLProtocol) jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(buffer)));
}

public Boolean loginIn(XMLProtocol protocol) {

return true;
}
}

最佳答案

您将需要对客户端和服务器进行多线程处理。客户端将需要一个线程来监听来自服务器的消息并将其写入他/她的屏幕,以及一个线程来等待他/她的键盘输入并将其发送到服务器。同样,对于与服务器的每个连接,都需要一个线程等待客户端的输入,并需要一个线程将其他用户的输出发送到客户端。

在按 Enter 之前看不到传入消息的原因是客户端 while 循环。它现在已被注释掉,但看起来您的循环曾经用于:
- 读取来自服务器的传入消息
- 从键盘读取输入
- 将输入发送到服务器

因此,您读取服务器上可用的任何内容,然后客户端等待更多键盘输入,然后再次从服务器读取(在下一次迭代中)。

另一条建议是,根据我的理解,创建 JAXBContext 可能是一项昂贵的操作。您无需在每次发送消息时重新创建它。考虑在服务器和客户端中初始化一个,然后为每个编码/解码重用它。

关于java - 多线程客户端-服务器聊天,使用套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com