Java客户端/服务器套接字

3
我是一个有用的助手,可以翻译文字。
我正在开始学习Java套接字,并遇到了奇怪的[缺少]输出。以下是套接字方法的源代码:
客户端源代码:
public void loginToServer(String host, String usnm ) {
    try {
        Socket testClient = new Socket(host,1042);
        System.out.println ("Connected to host at " + host);
        logString = ("CONNECTED: " + host);
        outGoing = new PrintWriter(testClient.getOutputStream(), true);
        outGoing.print("Hello from " + testClient.getLocalSocketAddress());
        InputStream inFromServer = testClient.getInputStream();
        DataInputStream in = new DataInputStream(inFromServer);
        System.out.println("Server says " + in.readLine());
        testClient.close();
    }
    catch (Exception e) {
        System.err.println ("Error connecting to host at " + host + ":1042.\n Reason: " + e);
        logString = ("CONNECT FAILED: " + host + ":1042: " + e);
    }
    printLog(logString);
    // send server usnm and os.name [System.getProperty(os.name)] ?
}

以下是服务器端的代码:

public void runServer() {
        try{
            server = new ServerSocket(1042); 
        }
        catch (IOException e) {
            printLog("LISTEN FAIL on 1042: " + e);
            System.err.println("Could not listen on port 1042.");
            System.exit(-1);
        }
        try{
            client = server.accept();
        }
        catch (IOException e) {
            printLog("ACCEPT FAIL on 1042: " + e);
            System.err.println("Accept failed: 1042");
            System.exit(-1);
        }
        try{
            inComing = new BufferedReader(new InputStreamReader(client.getInputStream()));
            outGoing = new PrintWriter(client.getOutputStream(), true);
        }
        catch (IOException e) {
            printLog("READ FAIL on 1042: " + e);
            System.err.println("Read failed");
            System.exit(-1);
        }
        while(true){
            try{
                clientData = inComing.readLine();
                //processingUnit(clientData, client);
                outGoing.print("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
            }
            catch (IOException e) {
            printLog("READ FAIL on 1042: " + e);
                System.out.println("Read failed");
                System.exit(-1);
            }
        }
    }

客户端的输出仅仅是 连接到本地主机

发生了什么?

2个回答

2

你正在编写文本并读取二进制。由于输出和输入不匹配,很可能会在这种情况下发生挂起。

我建议您使用writeUTF / readUTF进行二进制操作,或使用println/readLine进行文本操作。

顺便说一下:readUTF会读取两个字节以确定要读取的数据长度。由于前两个字节是ASCII文本,因此在返回之前您可能需要等待约16,000个字符。


非常感谢,我永远也猜不到这个。每种类型适用于哪些情况? - gossfunkel
文本适合发送可读的文字和数字。二进制适合高效、精确地发送数据。 - Peter Lawrey
这似乎并不是问题所在。修正了这个问题之后,服务器似乎没有执行 while 循环中的代码?它进入了循环,但没有试图或捕获异常... - gossfunkel
客户端和服务器都在等待对方发送一些文本。我会删除DataInputStream,因为它更可能会引起混淆而不是帮助。 - Peter Lawrey
为什么客户端在等待文本之前不向服务器发送文本? - gossfunkel

2

你正在读取行,但没有发送行。将print()更改为println()readLine()会一直阻塞等待换行符。当对等方关闭连接时,它将在流结束时返回null,但您也没有检查这一点,因此您将无限循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接