Hey, you had two problems in your code.
Firstly every time you want to send data accross a socket you need to call the flush(); method;
Ie after every out.println(); call out.flush(); this ensures that all data in the buffer is sent accross.
Secondly, on your server code you keep on using system.out.println to display the status and you are printing out in.readLine();
this will cause the server to hang since every time you call in.readLine() it waits for the client to send data.
Below is the code with modifications, note I added out.flush and I used a variable
String clientData = in.readLine() so that you only call in.readLine once.
I know you are doing this to test but when you get the hang of it you need to learn how to use sockets and threads together to allow multiple connections.
Ie, every time you call socket.accept()
you should launch a new
thread or call a thread from a thread pool to handle the request.
Hope this helps, good luck!.
import java.io.*;
import java.net.*;
public class server {
public static void main(String[] args) throws IOException {
listenSocket();
}
public static void listenSocket(){
ServerSocket server = null;
Socket client = null;
BufferedReader in = null;
PrintWriter out = null;
String line;
try{
server = new ServerSocket(20001);
System.out.println("starting local server on port 20001...");
}
catch (IOException e){
System.out.println("Could not listen on port 20001");
}
try{
client = server.accept();
}
catch (IOException e) {
System.out.println("Accept failed: 8123");
}
try{
//Establish a input stream from client socket
// * for reading data from client port
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//Establish a output stream to client socket
// * for writing data to client port
out = new PrintWriter(client.getOutputStream(), true);
}
catch (IOException e) {
System.out.println("Accept failed: 8123");;
}
// while(true)
{
try{
System.out.println("* starting to cope with client data *");
String clientData = in.readLine();
System.out.println("receive data from client (" + clientData + ")");
//line = in.readLine();
System.out.println("send data to client (" + clientData + ")");
out.println("This is a message from server");
out.flush();
}
catch (IOException e) {
System.out.println("Read failed");
e.printStackTrace();
}
}
}
}
import java.io.*;
import java.net.*;
class Client{
public static void main(String args[]){
try {
Socket socket = new Socket("localhost", 20001);
System.out.println("connecting to server localhost on port *20001*...");
//ready to send data to server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("This is the message from a client");
out.flush();
//ready to receive data from server
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
}
catch (UnknownHostException e){
System.out.println("Unknown host");
}
catch (IOException e){
e.printStackTrace();
}
}
}