gpt4 book ai didi

java - java中通过socket进行全双工通信

转载 作者:行者123 更新时间:2023-12-02 04:27:25 28 4
gpt4 key购买 nike

我可以使用两个不同的线程从同一个套接字读取和写入,而不需要在java中进行任何同步吗?

我的代码是 -

public class Server {

public static void main(String[] args) {
Serve s = new Serve();
}
}
class Serve {

ServerSocket sS;
String serverAddress;
int port;

public Serve() {
serverAddress = "127.0.0.1";
port = 8091;
try {
sS = new ServerSocket(port);
System.out.println("Server listening on port " + port+ " ...");
Socket incomming = sS.accept();
System.out.println("Connected to Client.");
Runnable r = new Read(incomming);
Runnable w = new Write(incomming);
Thread read = new Thread(r);
Thread write = new Thread(w);
read.start();
write.start();
incomming.close();
sS.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
class Read implements Runnable {

Socket readSocket;

public Read(Socket readSocket) {
this.readSocket = readSocket;
}

@Override
public void run() {
try {
InputStream inStream = readSocket.getInputStream();
try (Scanner in = new Scanner(inStream)) {
boolean done = false;
PrintWriter out = new PrintWriter(System.out, true);
while(!done && in.hasNextLine()) {
String line = in.nextLine();
out.println("Client>" + line);
if(line.trim().equals("BYE")) done = true;
}
}
}
catch(Exception e) {
e.printStackTrace();
}


}

}

class Write implements Runnable {

Socket writeSocket;

public Write(Socket writeSocket) {
this.writeSocket = writeSocket;
System.out.println("This is printed on the client terminal");
}

@Override
public void run() {
try {
OutputStream outStream = writeSocket.getOutputStream();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
PrintWriter out = new PrintWriter(outStream, true);
while(!done && in.hasNextLine()) {
System.out.print("Server>");
String line = in.nextLine();
out.println(line);
if(line.trim().equals("BYE")) done = true;
}
}
}
catch(Exception e) {
System.out.println("Exception thrown here");
e.printStackTrace();
}


}

}

两个问题 -

  1. Write 构造函数中的字符串正在客户端上打印。为什么会出现这种情况?

  2. 为什么Write run()方法会抛出异常?

最佳答案

Can I use two different threads to read and write from the same socket without any synchronization in java?

你无法避免同步,因为 Socket 的实现已经同步了。

如果只有一个线程读取,另一个线程写入,则可以避免额外同步。

The string in the Write constructor is getting printed on the client terminal. Why is this happening?

很可能是因为您也在客户端上运行该代码。

Why is the exception being thrown in the Write run() method?

您有一个错误,如果您阅读它并告诉我们它是什么(包括堆栈跟踪),则更容易诊断该错误

注意:线程的启动和运行需要时间。如果您立即关闭连接,则在您关闭连接之前,线程甚至可能没有机会读取连接。

    read.start();
write.start();
incomming.close(); // == kill the connection

而不是使用

 while(!done ...) {

if (condition)
done = true;
}

你可以使用

 while(...) {

if (condition)
break;
}

关于java - java中通过socket进行全双工通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966784/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com