我正在尝试制作某种登录系统,但服务器和客户端不会互相交谈。我不太清楚为什么他们不会互相交谈,但任何帮助都表示赞赏。
P.S端口在我的路由器上正确设置。
客户端
public class Clients implements Runnable
{
String ip = "localhost";
int port = 25565;
Socket client;
static Thread thread;
boolean setup = false;
BufferedReader br;
PrintWriter pw;
public static void main(String[] args)
{
thread = new Thread(new Clients());
thread.start();
}
public void run()
{
while(!setup)
{
try {
client = new Socket(ip,port);
setup = true;
} catch (IOException e) {
setup = false;
}
}
try {
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
pw = new PrintWriter(client.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.flush();
pw.write("client");
while(true);
}
}
服务器
public class Server implements Runnable
{
int port = 25565;
String input;
ServerSocket server;
Socket clients;
BufferedReader br;
PrintWriter pw;
boolean setup = false;
static Thread thread;
public static void main(String[] args)
{
thread = new Thread(new Server());
thread.start();
}
public void run()
{
try {
server = new ServerSocket(port);
clients = server.accept();
br = new BufferedReader(new InputStreamReader(clients.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("getting input");
while((input = br.readLine()) != null)
{
System.out.println(input);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我看到两个问题。第一个是pw.flush
之后应调用pw.write
。第二个是服务器正在等待readLine()
,它只会在遇到行结束时返回。您应该更改Clients
以调用pw.write("clients\n")
,添加换行符。
答案 1 :(得分:0)
你应该先写,然后刷新
pw.write("client\n");
pw.flush();
同样将\ n放在您正在编写的行中,因为在您正在执行的客户端br.readline().
所以它将等到新行可用。