roun512
roun512

Reputation: 149

Sending more than 1 message to TCP server in same connection

I've created a TCP Server in Java and a TCP client in Ruby. The problem is I'm not able to send more than 1 message in the same connection, Only the first message is sent while the other one is not sent.

here is the Java code

package com.roun512.tcpserver;

import java.io.*;
import java.net.*;

public class Program {


    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {

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

        while(true)
        {
            Socket connection = Socket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println(clientSentence);
            capitalizedSentence = clientSentence + '\n';
            outToClient.writeBytes(capitalizedSentence);
            System.out.println("Sent msg");
        }
    }
}

And here is the client code

Client.rb

require 'socket'
class Client

        def initialize()
                server = TCPSocket.open("127.0.0.1", 6789)
                if server.nil?
                        puts "error"
                else
                        puts "connected"
                end
                server.puts("Hello\r\n")
                sleep 2
                server.puts("There\r\n")
                server.close
        end
end
Client.new()

I'm only receiving Hello. I have tried many other ways but none worked.

So my question is how to send more than 1 message in a single connection, Any help would be appreciated :)

Thanks in advance!

Upvotes: 1

Views: 2461

Answers (1)

Oleg K.
Oleg K.

Reputation: 1549

Socket.accept() waits for new connection after reading the first line. Try the following:

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

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

    while (true)
    {
        Socket connection = Socket.accept();
        while(true)
        {
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println(clientSentence);
            capitalizedSentence = clientSentence + '\n';
            outToClient.writeBytes(capitalizedSentence);
            System.out.println("Sent msg");
        } 
    }
}

If it works, change while (true) to some meaningful condition and don`t fotget to close the connection after the work is done.

Upvotes: 4

Related Questions