gpt4 book ai didi

Java 套接字 : Connection but no Stream?

转载 作者:行者123 更新时间:2023-11-29 09:13:55 25 4
gpt4 key购买 nike

我正在尝试编写一个小的 SocketServer 和一个合适的 ClientApplet。连接有效(我回显传入/关闭连接),但服务器没有获得任何 InputStream。我只是无法解决问题,感觉有点失落:/

完整的项目是here .

这里是我的服务器负责的部分:

消息服务.java

public class MessageService implements Runnable {

private final Socket client;
private final ServerSocket serverSocket;

MessageService(ServerSocket serverSocket, Socket client) {
this.client = client;
this.serverSocket = serverSocket;
}

@Override
public void run() {
PrintWriter out = null;
BufferedReader in = null;
String clientName = client.getInetAddress().toString();
try {
out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line;
System.out.println("Waiting for "+clientName);

/* HERE I TRY TO GET THE STREAM */

while((line = in.readLine()) != null) {
System.out.println(clientName + ": " + line);
out.println(line);
out.flush();
}
}
catch (IOException e) {
System.out.println("Server/MessageService: IOException");
}
finally {
if(!client.isClosed()) {
System.out.println("Server: Client disconnected");
try {
client.close();
}
catch (IOException e) {}
}
}
}
}

部分客户

队列输出.java

public class QueueOut extends Thread {
Socket socket;
public ConcurrentLinkedQueue<String> queue;
PrintWriter out;

public QueueOut(Socket socket) {
super();
this.socket = socket;
this.queue = new ConcurrentLinkedQueue<String>();
System.out.print("OutputQueue started");
}

@Override
public void start() {
try {
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Running outputqueue");
while(true) {
if(this.queue.size() > 0) {
String message = this.queue.poll();
System.out.println("Sending "+message);
out.println(message+"\n");
}
}
}
catch (IOException ex) {
System.out.println("Outputqueue: IOException");
}
}

public synchronized void add(String msg) {
this.queue.add(msg);
}
}

我已将我的帖子缩减为(我认为)必要的部分 :)

最佳答案

尝试在获取输出流之前获取输入流,即使您没有使用它,您也应该在客户端和服务器上匹配相反的顺序(如另一个类似线程中所讨论的)。

编辑:

另见 Socket programming

祝你好运!

关于Java 套接字 : Connection but no Stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10674551/

25 4 0