java - TCP 客户端/服务器程序,DataInputStream/DataOutputStream 问题

标签 java sockets tcp

我正在尝试编写一个简单的 TCP 客户端服务器连接。服务器为每个新的客户端连接生成一个线程,每个线程都与客户端通信。我正在使用 DataInputStream 和 DataOutputStream 类,在 dis.readUTF() 服务器线程停止时。我尝试使用 BufferedReader 和 PrintStream/Printwriter,仍然是同样的问题。请查找 System.out.println("not here now"),它前面的那一行会阻止执行。

/*
TCP client
*/

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient {

    public TCPClient() {
        // TODO Auto-generated constructor stub

    }

    public static void main (String args[]) throws UnknownHostException, IOException {

        Socket socket = new Socket("localhost", 9701);

        DataInputStream input = new DataInputStream(socket.getInputStream());

        DataOutputStream output = new DataOutputStream(socket.getOutputStream());

        //char[] buffer = new char[100];

        boolean stop = false;

        while (!stop) {

            System.out.println("here");
            output.writeBytes("hello server");

            String response = "-WTF-";
            System.out.println("here");

            response = input.readUTF();
            System.out.println("not here now");

            if (response == "kill") {
                stop = true;
            } else {
                System.out.println("5");
                output.writeBytes("talk to me");                
                System.out.println("received" + response);
            }
        }
        socket.close();
    }
}


/* TCP server */

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class TCPServer extends Thread {

    final static int TCP_SERVER_PORT = 9701;
    private Socket socket;

    public TCPServer(Socket sock) {
        // TODO Auto-generated constructor stub
        socket = sock;

    }

    public void run()  {

        System.out.println(this.socket.getPort() + " working or sleeping for 5 seconds");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        DataInputStream clientinp;
        DataOutputStream clientout;

        try {
            clientinp = new DataInputStream(socket.getInputStream());
            clientout = new DataOutputStream(socket.getOutputStream());
            System.out.println("here");

            while (true) {
                System.out.println("here now");
                String sentence = clientinp.readUTF();   
                System.out.println("not here now");
                System.out.println(sentence);
                clientout.writeBytes(sentence);

            }

        }
        catch (IOException e) {

            System.out.println(e.getStackTrace());
        }
        finally {

            try {
                this.socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /*
         * other logic
         */     
    }

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

        ServerSocket serversocket;

        serversocket = new ServerSocket(TCP_SERVER_PORT);

        while (true) {
            Socket clientsocket = serversocket.accept();

            new TCPServer(clientsocket).start();

        }       
    }
}

最佳答案

您正在使用 writeBytes 在客户端写入字符串,并使用 readUTF 在服务器读取相同的字符串。

如果您查看这两种方法的 javadoc,您会发现您正在以一种格式编写,然后以另一种格式读取。具体来说,readUTF 期望输入以 2 字节字符计数开头,后跟字符的“修改后的 UTF-8”编码。但是 writeBytes 只是为每个字符写入 1 个字节。通常,readUTF 将尝试读取比 writeBytes 写入更多的字节...并且套接字流将卡住。

您应该使用 writeUTF 而不是 writeBytes ...

关于java - TCP 客户端/服务器程序,DataInputStream/DataOutputStream 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187038/

相关文章:

java - 按钮、JTextFields 和 JComboBox 是不可点击的

c++ - 套接字描述符在分配后关闭

networking - 如何将网络请求分派(dispatch)到(地理上)最近的服务器

c#异步TCP服务器阻塞客户端

java - jetty 赛跑者。 PWC6349 : Cannot find a java compiler for compilation

java - 如何在 Eclipse 中生成 Javadoc 注释?

c# - 如何为包含 ManualResetEvent.WaitOne() 的异步(套接字)代码编写单元测试?

linux - 接口(interface)的 'primary address'是什么意思

java - TCP - 如何在本地主机服务器上的两个玩家之间玩 java 游戏

java - 将 JPanel 转换为 JScrollPane 中的图像