gpt4 book ai didi

java - 输出.println(); Java SocketServer 不工作

转载 作者:行者123 更新时间:2023-11-30 06:03:23 24 4
gpt4 key购买 nike

我正在尝试通过客户端向服务器发送消息,但我在服务器上看不到该消息。它表明它连接正确。我认为这个问题与 Client 类中的此有关,但我不太确定。如果有人有解决方案,请告诉我。

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String send = reader.readLine();
out.println(send);
out.flush();

这是客户端类:

package com.evolution.client;

import java.net.*;
import java.io.*;
public class Client {
private Socket client;
private PrintWriter out;
private BufferedReader in;

public static void main(String[] args) {
Client client = new Client();
client.startConnection("localhost", 325);
}
public void startConnection(String ip, int port) {
try {
client = new Socket(ip, port);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Connected");
out.println("Connection started from, " + client.getLocalAddress());
out.flush();
while (true) {
String recieve = in.readLine();
System.out.println(recieve);

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String send = reader.readLine();
out.println(send);
out.flush();
}
} catch (Exception e) {
System.out.println(e);
}
}

public void stopConnection() {
try {
in.close();
out.close();
client.close();
}
catch (Exception e) {

}
}
}

这是服务器类文件:

package com.evolution.server;

import java.io.*;
import java.net.*;

public class Server {
private int port = 325;
private ServerSocket server;
private Socket client;
private PrintWriter out;
private BufferedReader in;

public static void main(String[] args) throws IOException {
Server server = new Server();
System.out.println("Start Up!");
server.start(server.port);
}

public void start(int port) throws IOException {
server = new ServerSocket(port);
try {
while (true) { //always runs unless break;
client = server.accept();
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out - send output

String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.equalsIgnoreCase("shutdown"))
stop();
System.out.println(inputLine);
}
}
}
finally { //runs no matter what after try {}
server.close();
}
}
public void stop() {
try {
in.close();
out.close();
client.close();
server.close();
System.exit(0);
}
catch (Exception e) {
}
}
}

如果您有任何可能的解决方案,请告诉我。

最佳答案

线路String receive = in.readLine();在客户端将阻止( BufferedReader readLine() blocks )。由于服务器没有发送更多行,因此您的代码被卡在那里。

删除此行允许您从客户端向服务器发送消息。

关于java - 输出.println(); Java SocketServer 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51830236/

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