I wrote some program that has to receive and send messages. But I have some troubles with streams. I start my server and program. Then I'm trying send message, but my program just freezes. I used telnet and it works. I use sockets in this project and try do some messenger.
我写了一些程序,必须接收和发送消息。但我对溪流有一些问题。我启动我的服务器和程序。然后我试着发送消息,但我的程序就是死机了。我使用了远程登录,它起作用了。我在这个项目中使用套接字,并尝试做一些信使。
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
button.addActionListener(e ->{
try {
out.write(textField.getText() + "\n");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
try {
textArea.append(in.readLine()+"\n");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
textArea.setCaretPosition(textArea.getText().length());
textField.setText("");
});
setVisible(true);
}
public static void main(String[] args) throws IOException {
new Main().Draw();
}
}
public class Server {
private static ArrayList<Receiver> receivers = new ArrayList<>();
public static ArrayList<Receiver> sockets(){
return receivers;
}
public static void main(String[] args) {
try(ServerSocket serverSocket = new ServerSocket(4040)){
while (true){
Socket socket = serverSocket.accept();
receivers.add(new Receiver(socket));
}
}
catch (IOException e){
e.printStackTrace();
}
}
@Override
public void run() {
String message = null;
while (true){
try {
message = in.readLine() + "\n";
} catch (IOException e) {
throw new RuntimeException(e);
}
for(Receiver socket : Server.sockets()) {
try {
socket.out.write("Your message: " + message+"\n");
socket.out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
更多回答
Lack of any visible threading looks suspicious.
没有任何可见的线看起来很可疑。
You are ignoring end of stream here: in.readLine()
. It will return null at end of stream, at which point you should close the socket and stop reading.
您在这里忽略了流的结束:in.readLine()。它将在流的末尾返回NULL,此时您应该关闭套接字并停止读取。
You will be blocking the EDT. Almost never can you expect a GUI to work with network IO without multithreading. Look at the excellently-documented SwingWorker
你会挡住美国东部夏令时。几乎不可能指望图形用户界面在没有多线程的情况下与网络IO一起工作。看看记录精良的SwingWorker吧
我是一名优秀的程序员,十分优秀!