简体   繁体   中英

Sending and receiving TCP simuntainously

I'm trying to create a TCP client/server that sends and receives messages. My problem right now is that I can't do them both simultaneously. I'm sending a message to the server and reading it just fine, but after each received message to the server, I also want to send back a response to the client acknowledging it.

I'm sending several messages per second to the server, but when I try to re-send a message to the client, it just gets stuck, no message on either end. I can however send in either direction, client to server and server to client, but only one way.

This is the client handler for the server:

public TCPClientHandler(Socket client, int bufferSize) throws IOException {
    this.client = client;
    messageToClient = new PrintWriter(client.getOutputStream(),true);
    recvFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
    buffer = new byte[bufferSize];
}
    
@Override
public void run() {
    try {
        /* Read the data from the client.
         * If the message is larger than the server buffer we close the connection.
         * If the client closes connection we get exception and we catch it
         * at the end.
         */
        while (true) {
            if (recvFromClient.readLine().getBytes().length > buffer.length){
                break;
            }
            /* Receiving and printing message */
            buffer = Arrays.copyOf(recvFromClient.readLine().getBytes(),
                recvFromClient.readLine().getBytes().length);
    
            String messageFromClient = new String(buffer,StandardCharsets.UTF_8);
            System.out.println("Client message: " + messageFromClient);
            messageToClient.println();
    
            /* Sending message to client */
        }
    
    } catch (IOException e) {
        System.out.println("Connection to client lost...");
    } finally {
        System.out.println("Connection closed on thread " + Thread.currentThread().getName());
        messageToClient.close();
        try {
            recvFromClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }            
}

This is the client:

public class TCPEchoClient {

    /*
    Args input
    1. Server Address
    2. Server Port
    3. Socket Buff Size
    4. Transfer Rate
    5. Message
     */
    public void run(String args[]){
        try {
            // Dummy values
            InetAddress host = InetAddress.getByName("localhost");
            int serverPort = 4950;
            int buffSize = 100;
            int transferRate = 5;
            String echoMessage = "112312451265214126531456234321";
            String receive;

            System.out.println("Connection to server on port " + serverPort);

            Socket socket = new Socket(host,serverPort);
            socket.setReceiveBufferSize(buffSize);
            System.out.println("Just connected to " + ocket.getRemoteSocketAddress());

            // Writer and Reader to write and read to/from the socket.
            PrintWriter writeToServer = new PrintWriter(socket.getOutputStream(),true);

            BufferedReader recvFromServer = new BufferedReader(new `InputStreamReader(socket.getInputStream()));`

            if (transferRate < 1){
                writeToServer.println(echoMessage);
            }else {
                // Continuously send messages with 1 second between x amount of
                // messages, until client is aborted.
                while (true) {
                    for (int i = 0; i < transferRate; i++) {
                        writeToServer.println(echoMessage);
                        receive = new String(recvFromServer.readLine().getBytes(), StandardCharsets.UTF_8);
                        System.out.println(receive);
                    }
                    Thread.sleep(1000);
                }
            }

            // Close reader/writer and socket
            writeToServer.close();
            recvFromServer.close();
            socket.close();

        } catch (SocketException e){
            System.out.println("Socket exception...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TCPEchoClient client = new TCPEchoClient();
        client.run(args);
    }
}

I would like to read the messages that are transmitted as bytes, store them in the buffer, and THEN read the message, but so far no success.

Fixed the issue. I moved the receive part inside the client to AFTER the thread sleep.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM