【发布时间】:2015-04-05 22:16:34
【问题描述】:
我正在测试套接字,因此您必须原谅凌乱的代码,但我在让套接字服务器接收套接字发送的消息或发送消息时遇到了一些问题。无论哪种方式,我都无法弄清楚出了什么问题。
我的代码开始侦听来自附加套接字点的消息,但没有到达停止的侦听点,并且没有错误,因此它是从输入流中读取的。但是,当我写入一些内容并将其写入套接字的 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();
}
}
【问题讨论】: