gpt4 book ai didi

Java 服务器套接字响应

转载 作者:搜寻专家 更新时间:2023-10-31 19:46:23 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的客户端/服务器套接字通信应用程序(聊天客户端)。我花了无数个小时寻找如何解决这个问题,但仍然没有运气,我可以将消息发送到服务器,但我无法将消息从服​​务器发送回客户端。

我认为问题在于消息发回后我如何从服务器获取消息,我删除了我拥有的 InputStreamReader,我无法开始工作。

(我提前为草率的代码道歉)

服务器.java

public class Server extends Thread {
@SuppressWarnings("unused")
private static Socket socket;
static int port = 1337;
static ObjectOutputStream output;

@SuppressWarnings("resource")
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(port);
System.out.println("Server started on port: " + port);
while(!Thread.interrupted()){
try {
Socket clientSocket = ss.accept();
DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
PrintStream output = new PrintStream(clientSocket.getOutputStream());
String str = (String)dis.readUTF();
String[] split = str.split("-");
String subStringUsername = split[0];
String subStringMessage = split[1];
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
String formattedTimestamp = sdf.format(date);
System.out.println("Message from " + subStringUsername + ": " + subStringMessage + " - at " + formattedTimestamp);
output.flush();

output.println("Message received! Hello client!");
System.out.println("Reply sent");
output.flush();

//TODO create new thread handle new users instead of Thread sleep
//TODO chat commands and user ID / can't be existing user

Thread.sleep(500);
}
catch(Exception e){
System.out.println(e);
}
}
}

getMessage.java

public class GetMessage extends Thread {    
public void run(){
while(true) {
InputStreamReader be = new InputStreamReader();
}
}
}

这是 getMessage 类的剩余内容,因为我沮丧地删除了所有内容,我将 getMessage 作为线程运行,我不知道这是不是最好的方法。我已经尝试了 10 种方法从服务器获取消息,但仍然不走运,如果有人能指出我正确的方向,我将不胜感激。

最佳答案

readUTF 阻塞直到它接收到输入结束,并且应该只读取通过 writeUTF 方法传递的数据。

引用:更完整的讨论。

readUTF() causing Android app to hang

Also check out the docs

你可能会想要替换

DataInputStream dis = new DataInputStream(clientSocket.getInputStream());

 BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));

 dis.readUTF();

String str = reader.readLine();

或者,如果您不使用新行来标记消息的结尾

char[] buffer = new char[1024];
int read = 0;
StringBuilder sb = new StringBuilder();

while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
sb.append(buffer, 0, read);
// conduct some test that when passes marks the end of message, then break;
}
reader.close();

String str = sb.toString().trim();

关于Java 服务器套接字响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20554220/

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