Can anyone help me debug this program?
The following is server code :
package networking;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
while (true) {
Socket client = serverSocket.accept();
Scanner reader = new Scanner(client.getInputStream());
PrintWriter writer = new PrintWriter(client.getOutputStream());
String inputString = reader.nextLine();
System.out.println("Received from client : " + inputString);
writer.write(inputString.toUpperCase());
client.close();
}
}
}
And this is the client code :
package networking;
import java.io.PrintWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
class TcpClient {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost", 5555);
PrintWriter writer = new PrintWriter(client.getOutputStream());
Scanner reader=new Scanner(client.getInputStream());
writer.println("oPen SOurCe RUleS !");
System.out.println("Received from server : "+reader.nextLine());
client.close();
}
}
The pro开发者_如何转开发blem is that when I run this program both client & server go into indefinite waiting state.Could anyone tell me what's wrong with this code?
Thanks in advance!
Have you tried Flushing the PrintWriter
?
You close the stream but you never notify the writer that you're about to do so.
精彩评论