首页 文章

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

提问于
浏览
2

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

/*
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();

        }       
    }
}

2 回答

  • 8

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

    如果您查看这两种方法的javadoc,您将看到您正在以一种格式书写,然后在另一种格式中阅读 . 具体来说, readUTF 期望输入以2字节字符计数开始,然后是字符的"modified UTF-8"编码 . 但 writeBytes 只是每个字符写入1个字节 . 通常, readUTF 将尝试读取比 writeBytes 写入更多的字节...并且套接字流将冻结 .

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

  • 3

    斯蒂芬C是对的 . 我做了一些小修改,但原因是'在另一边使用write *时使用read *' .

    这是运行代码:
    客户:

    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() {
        }
    
        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());
    
            boolean stop = false;
            while (!stop) {
                System.out.println("client->server: hello...");
                output.writeUTF("hello");
    
                System.out.println("client: waiting...");
                String response = input.readUTF();
                System.out.printf("client: got response: %s\n", response);
            }
            socket.close();
        }
    }
    

    服务器:

    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) {
            socket = sock;
        }
    
        public void run() {
            System.out.println(this.socket.getPort() + " working or sleeping for 5 seconds");
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            DataInputStream clientinp;
            DataOutputStream clientout;
    
            try {
                clientinp = new DataInputStream(socket.getInputStream());
                clientout = new DataOutputStream(socket.getOutputStream());
    
                while (true) {
                    System.out.println("reading...");
                    String sentence = clientinp.readUTF();
                    System.out.printf("read: %s", sentence);
                    clientout.writeUTF(String.format("answer: %s", sentence));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        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();
            }
        }
    }
    

相关问题