Hi,
I want to implament a simple tcp client and server.
but I want my clien do I need to init the socket before every time I'm sending message to the server ?
This is my client:

class TCPClient {
    public static void main(String argv[]) throws Exception {
        String sentence = "1";
        String modifiedSentence;
        Scanner userInput = new Scanner(System.in);

        Socket clientSocket =null;


        while (!sentence.equals("q")) {
                clientSocket = new Socket("127.0.0.1", 6789);

            DataOutputStream outToServer = new DataOutputStream(
                    clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
            sentence = userInput.nextLine();
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
            System.out.println("FROM SERVER: " + modifiedSentence);

        }
        clientSocket.close();   

    }
}

as you can see I init the clientSocket every loop.
I try to copy the clientSocket init outside of the loop and my messages is not being send to the server.
can any one help me out in this one ?

My server:

class TCPServer {
    public static void main(String argv[]) throws Exception {

        String clientSentence;
        String capitalizedSentence;

        ServerSocket welcomeSocket = new ServerSocket(6789);
        System.out.println("server is up");

        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(
                    new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(
                    connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("Received: " + clientSentence);
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
        }
    }
}

No, you would normally open the socket connection once, send all your data, then close the connection. Opening and closing for every message is unnecessary unless there are very long time intervals between the messages. You will need to flush the output stream after each message if you expect an immediate reply.
If you post your modified code we'll have a look at it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.