Reputation: 63
I'm trying to learn how to use threads alongside sockets in java. I have a very simple program. Its function is to have the user input a string and to have that message received and printed out by the server whose socket is running inside of a thread. I get it to print out "Connection established!" and to accept inputs from the user, but they never seem to print out. Is there some reason why received messages aren't being printed to the console?
Here is the Client class:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
InetAddress host = InetAddress.getLocalHost();
TCPServer newServer = new TCPServer(5001);
Thread thread = new Thread(newServer);
thread.start();
Socket socket = new Socket(host,5001);
String outgoing_message = "";
Scanner scan = new Scanner(System.in);
PrintWriter printer = new PrintWriter(socket.getOutputStream());
while(!outgoing_message.equals("close")) {
System.out.print("Enter message: ");
outgoing_message = scan.nextLine();
printer.println(outgoing_message);
}
socket.close();
}
}
And here is the TCPServer class:
package Package_Two;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TCPServer implements Runnable{
private Socket socket;
private ServerSocket serverSocket;
public TCPServer(int port) throws IOException{
this.serverSocket = new ServerSocket(port);
}
@Override
public void run(){
try {
this.socket = serverSocket.accept();
System.out.println("Connection established!");
Scanner scan = new Scanner(socket.getInputStream());
String incoming_message = "";
while(!incoming_message.equals("close")){
incoming_message = scan.nextLine();
System.out.println("Received message: " + incoming_message);
}
socket.close();
}
catch(IOException iex){
iex.printStackTrace();
}
}
}
Upvotes: 0
Views: 94
Reputation: 3584
If you will take a look at source code of PrintWriter
constructor you used, you will spot that it invoke another constructor with autoFlush = false
.
I suppose, you should change it to:
PrintWriter printer = new PrintWriter(socket.getOutputStream(), true);
Upvotes: 1