gpt4 book ai didi

java - 套接字通过缓冲读取器读取,而不是在线拾取

转载 作者:行者123 更新时间:2023-12-01 11:41:51 25 4
gpt4 key购买 nike

我正在测试套接字,因此您必须原谅这些困惑的代码,但是我在让套接字服务器拾取套接字发送的消息或发送消息时遇到了一些问题。不管怎样,我不知道出了什么问题。

我的代码开始监听来自附加套接字点的消息,但没有到达停止的监听点,并且没有错误,因此它正在从输入流读取。但是,当我写入一些内容并将其写入套接字的 OutputStreamWriter 时,套接字的缓冲读取器(由套接字服务器接受)不会接收到它。

任何帮助都会很棒。谢谢。

public class Main
{
private static final String _address = "127.0.0.1";
private static final int _port = 8080;

private static ServerSocket _listener;

private static Socket _socket;
private static OutputStreamWriter _socketWriter;

public static void main(String[] args) throws Exception {
System.out.println("Type something in to send it into the big wide world!\n\nType quit to exit.");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
Main._startListening();
Main._connectToListener();

while(true) {
String msg = inputReader.readLine();

if("".equals(msg)) {
System.out.println("You can't send nothing!");
continue;
}
else if("quit".equals(msg)) {
Main._listener.close();
break;
}

Main.sendMessage(msg);
}
}

public static void sendMessage(String message) throws Exception {
System.out.println("Sending " + message);
Main._socketWriter.write(message + System.getProperty("line.separator"));
}

private static void _connectToListener() throws Exception {
Main._socket = new Socket(Main._address, Main._port);
Main._socketWriter = new OutputStreamWriter(Main._socket.getOutputStream());
System.out.println("Connected to listener");
}

private static void _startListening() throws Exception {
Main._listener = new ServerSocket(Main._port);

new Thread(new Runnable()
{
@Override
public void run() {
System.out.println("Listening on " + Main._address + ":" + Main._port);

while (!Main._listener.isClosed()) {
try {
final Socket socket = Main._listener.accept();

System.out.println("Attached new socket " + socket.getInetAddress().toString());

new Thread(new Runnable()
{
@Override
public void run() {
System.out.println("Listening for messages from attached socket");

try {
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while(!socket.isClosed()) {
String receivedLine = socketReader.readLine();
System.out.println("Received " + receivedLine);
}

System.out.println("Stopped listening to socket " + socket.getInetAddress().toString());
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}).start();
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
}).start();
}
}

最佳答案

经典。您正在阅读台词,但您没有发送台词。您需要在消息中附加行终止符。

关于java - 套接字通过缓冲读取器读取,而不是在线拾取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462854/

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