I can't understand why the code below doesn't work. The client sends a message to the server, and the server prints the message to standard output.
Code for the server:
import java.net.*;
import java.io.*;
import java.math.BigInteger;
public class server
{
public static void main(String args[])
{
try
{
ServerSocket server = new ServerSocket(8080);
while (true)
{
// initializations
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out = new PrintWriter(connection.getOutputStream());
// listen for client message
String message = in.readLine();
// print raw message from client
System.out.println(message);
// close resources
if (out != null)
out.close();
if (in != null)
in.close();
if (connection != null)
connection.close();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
System.exit(1);
开发者_如何学JAVA }
}
}
Code for the client:
import java.net.*;
import java.io.*;
import java.math.BigInteger;
public class client
{
public static void main(String args[])
{
try
{
// initializations
Socket connection = new Socket("localhost", 8080);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out = new PrintWriter(connection.getOutputStream());
// send message to server
out.println("Hello, world!");
// close resources
if (in != null)
in.close();
if (out != null)
out.close();
if (connection != null)
connection.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
System.exit(1);
}
}
}
Any insights? Thanks!
What you should be doing to figure out this type of problem, is to isolate where the problem comes from. Is it the Server portion, or the client portion? An easy test for the server is to start it up, then telnet to that port (ex. "telnet 127.0.0.1 8080") type in something and see if it is outputing. (btw, your server code works fine).
Doing this would allow you to focus on your client code. As Affe stated, you simply didn't flush out the input stream. Learning methodologies for troubleshooting code is at least as important as learning to write code.
Also as an aside, by convention, Java classes start with a capital letter, so it should be "Server" and "Client"
That default PrintWriter does not autoflush. (and doesnot flush on close as abstract Writer deceptively may lead you to believe. Either do:
PrintWriter out = new PrintWriter(connection.getOutputStream(), true);
or else
out.println("Hello, world!");
out.flush();
Add a flush after you write to the stream in your client :
// send message to server
out.println("Hello, world!");
out.flush();
Also Make sure the server socket is not blocked by firewall
精彩评论