我正在尝试创建一个简单的客户端/服务器套接字通信应用程序(聊天客户端)。我花了无数小时来寻找如何解决此问题的方法,但是仍然没有运气,我可以将消息发送到服务器,但是我仍然坚持将消息从服务器发送回客户端。
我认为问题在于发送回服务器后如何从服务器获取消息,我删除了我以前无法使用的InputStreamReader。
(我对松散的代码表示歉意)
Server.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作为线程运行,我不知道这是否是最好的方法。我尝试了十种方法来从服务器获取消息,但仍然不走运,如果有人可以向我指出正确的方向,我将不胜感激。
最佳答案
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();