Java客户端/服务器套接字

时间:2012-05-31 16:08:42

标签: java sockets client serversocket

我开始使用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);
            }
        }
    }

客户提供的输出仅为Connected to host at localhost

发生了什么事?

2 个答案:

答案 0 :(得分:2)

您正在撰写文字和阅读二进制文件。由于您的输出和输入不匹配,因此很可能会挂起。

我建议您使用带有writeUTF / readUTF的二进制文件或带有println / readLine的文本。

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

答案 1 :(得分:2)

您正在阅读线路,但您没有发送线路。将print()更改为println()readLine()将永远阻止等待换行符。它将在流的末尾返回null,即当对等体关闭连接时,但你没有检查它,所以你无限期地循环。