Java服务器套接字响应 [英] Java Server Socket Response

查看:161
本文介绍了Java服务器套接字响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a simple client/server socket communication application (chat client). I've spent countless hours looking on how to fix this with still no luck, I can send the message to the server but I'm stuck with sending the message back from the server to the client.

我认为问题是我在收到邮件后从服务器收到邮件的方式,我删除了我所拥有的InputStreamReader,这是我无法工作的。

I believe the issue is how I'm getting the message from the server after it's sent back, I deleted what I had which was an InputStreamReader which I couldn't get to work.

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

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作为一个线程运行,我不知道这是最好的方法。我已经尝试了10种方法从服务器获取消息仍然没有运气,如果有人能指出我正确的方向我会非常感激。

This is what I have left of the getMessage class as I deleted everything in frustration, I'm running getMessage as a thread which I don't know is the best way or not. I've tried 10's of methods to get the message from the server with still not luck, if someone could point me in the right direction I would be greatly appreciative.

推荐答案

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

readUTF blocks until it receives end of input, and should only be reading data that passed through the writeUTF method.

参考:进行更完整的讨论。

reference: for a more complete discussion.

readUTF()导致Android应用程序要挂起

还查看文档

您可能想要替换

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

with

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

 dis.readUTF();

with

String str = reader.readLine();

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

or, if you are not using new lines to mark the end of a message

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服务器套接字响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆