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);
}
}
}