Ber*_*ard 0 java connection networking multithreading
如果分开
客户端---发送消息到--->服务器:工作正常!
如果分开
服务器---发送消息到--->客户端:工作正常!
但是当两者在一起时:
客户端---发送消息到--->服务器
服务器---发送消息到--->客户端
什么都行不通!
这是ServerSide:
import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MyServer
{
private final static int port = 8000;
private static String hostname = "";
private static String hostIP ="";
public static void main(String[] args )
{
ServerSocket serverSocket=null;
try {
// get host information
hostname = InetAddress.getLocalHost().getHostName();
hostIP = InetAddress.getLocalHost().getHostAddress();
// display server information
System.out.println("MyServer started on "+hostname+" with IP: "+hostIP + " on the port number: " + port);
serverSocket = new ServerSocket(port);
}
catch(IOException e)
{
e.printStackTrace();
}
while(true)
{
ClientWorker w;
try
{
w = new ClientWorker(serverSocket.accept());
Thread t = new Thread(w);
t.start();
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
}
class ClientWorker implements Runnable
{
Socket incoming;
public ClientWorker(Socket incoming)
{
this.incoming = incoming;
}
public void run()
{
String request = null;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
request = in.readLine();
System.out.println("request =" + request);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter out = null;
try {
out = new PrintWriter(incoming.getOutputStream(),true);
} catch (IOException e) {
e.printStackTrace();
}
out.println("The command is not readable");
}
Run Code Online (Sandbox Code Playgroud)
}
这是ClientSide:
import java.io.*;
import java.net.*;
public class MyClient2
{
public static void main(String[] args)
{
String answer = null;
if (args.length != 1){
System.out.println("Usage: MyClient serverHostname");
System.exit(0);
}
try
{
Socket socket = new Socket (args[0], 8000);
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
out.print("TIME");
System.out.println("Request has been send");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
answer = in.readLine();
System.out.println("The answer is: "+answer);
in.close();
out.close();
socket.close();
}
catch (Exception e)
{
System.out.println("Make sure the server is running and try again");
}
}
}
Run Code Online (Sandbox Code Playgroud)
请看一下,感谢您的评论.干杯
您正在使用readLine阻塞的方法,直到读取换行符或关闭流.您既不发送换行符也不关闭流(直到您希望收到回复之后).
尝试out.print("TIME");改为out.println("TIME");.
此外,避免使用PrintWriter,因为它隐藏了发生的任何IOExceptions,您必须手动检查.你的异常处理不是很好.当发生IOException时,您可能应该终止该线程(而不是盲目地继续),因为您无法从错误中恢复.
此外,你ClientWorker不会自己清理 - 即.关闭流和套接字.
| 归档时间: |
|
| 查看次数: |
3182 次 |
| 最近记录: |