Java TCP - 服务器&客户工作,但无法得到答案

时间:2016-10-08 18:41:15

标签: java tcp

我试图制作一个小型的TCP服务器/客户端。我有一个客户端和一个服务器,在解决了一些基本的异常后,没有任何作用。 客户端应该将(用户)数据发送到服务器(在端口6789,localhost),然后应该以大写形式将其写入并将其结束。一切似乎都有效,除了发回大写字母。这是代码:

TCPSERVER:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

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

        System.out.println("SERVER");

        String clientSentence;
        String capitalizedSentence;
        ServerSocket server = new ServerSocket(6789);


        TCPClient.main(null);


        while (true) {
            Socket connection = server.accept();
            System.out.println("<S> Connection!");
            BufferedReader fromClient = new BufferedReader(
                new InputStreamReader(connection.getInputStream()) );
            DataOutputStream toClient = new DataOutputStream(connection.getOutputStream());

            clientSentence = fromClient.readLine();
            System.out.println("<S> Recieved: " + clientSentence);

            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            System.out.print("About to send: " + capitalizedSentence);
            toClient.writeBytes(capitalizedSentence);
        }
    }

}

的TcpClient:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class TCPClient {

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

        System.out.println("CLIENT");

        String sentence;
        String modSentence;
        BufferedReader inUser = new BufferedReader(new InputStreamReader(System.in));

        Socket clientToServer = new Socket("localhost", 6789);
        DataOutputStream outServer = new DataOutputStream(clientToServer.getOutputStream());
        BufferedReader inServer = new BufferedReader(
            new InputStreamReader(clientToServer.getInputStream()) );

        System.out.println("<C> Type now: ");
        sentence = inUser.readLine();
        System.out.println("<C> Got it!");

        System.out.println("<C> Sending " + sentence + " to server...");
        outServer.writeBytes(sentence + '\n');
        outServer.flush();

        System.out.println("<C> Server respodse:");
        modSentence = inServer.readLine();

        System.out.println("<C> From server: " + modSentence);
        clientToServer.close();
    }
}

控制台:

SERVER
CLIENT
<C> Type now: 
efd
<C> Got it!
<C> Sending efd to server...
<C> Server respodse:
asd

和...

没有

2 个答案:

答案 0 :(得分:1)

答案是: 我很蠢。

我不小心让客户端和服务器都运行在同一个线程上。我现在TCPClient一个Runnable,一切都按计划进行。

注意: TCPClient.main(null)不会启动新的程序/线程,只是同一个线程,另一个静态函数。

答案 1 :(得分:0)

您正在冲洗客户端方面 - 但不是在服务器端!

只需添加

即可
toClient.flush()

也在服务器端打电话!