我正在编写一个Java客户端应用程序(带有TCP/IP的基本Java Net包)。客户端必须从system.in获取输入,同时必须通过套接字输入流监听来自服务器的任何消息。一旦接收到来自system.in的输入,客户端将获得该输入,执行一些处理,并将其作为请求发送到服务器。所以基本上有两个进程在运行,
-listening到客户端的请求
服务器响应的-listning。
为此,我实现了两个线程,并在主线程中运行消息处理。这是足够好的设计吗?
并且是否存在将从system.in接收到的消息返回到主线程的方法。线程run()方法返回void。我使用了一个易失性变量来返回收到的字符串,但它说易失性是非常昂贵的,因为它不使用cpu缓存来存储变量。
发布于 2015-01-26 18:18:36
您可以查看我为java套接字和多线程编写的这两个项目。
我猜你想要的是ClientExample,但你也可以看看服务器部分。
基本上,我们的想法是启动两个独立的线程来监听不同的输入-套接字和控制台。
final Thread outThread = new Thread() {
@Override
public void run() {
System.out.println("Started...");
PrintWriter out = null;
Scanner sysIn = new Scanner(System.in);
try {
out = new PrintWriter(socket.getOutputStream());
out.println(name);
out.flush();
while (sysIn.hasNext() && !isFinished.get()) {
String line = sysIn.nextLine();
if ("exit".equals(line)) {
synchronized (isFinished) {
isFinished.set(true);
}
}
out.println(line);
out.flush();
disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
};
};
outThread.start();和另一个用于套接字输入的线程:
final Thread inThread = new Thread() {
@Override
public void run() {
// Use a Scanner to read from the remote server
Scanner in = null;
try {
in = new Scanner(socket.getInputStream());
String line = in.nextLine();
while (!isFinished.get()) {
System.out.println(line);
line = in.nextLine();
}
} catch (Exception e) {
// e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
};
};
inThread.start();我希望这会对您有所帮助:)
https://stackoverflow.com/questions/28148060
复制相似问题