gpt4 book ai didi

JAVA Socket编程死循环

转载 作者:行者123 更新时间:2023-11-29 08:56:39 27 4
gpt4 key购买 nike

这是我的套接字编程代码...

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

public class EchoClient
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("127.0.0.1",9999);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(),true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;

do
{
line = r.readLine();

if (line != null)
{ System.out.println(line); }

line = con.readLine();
w.println(line);
}
while(!line.trim().equals("bye"));
}

catch(Exception err)
{ System.err.println(err); }
}
}

服务器代码:

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

public class EchoServer
{
public EchoServer(int portnum)
{
try
{ server = new ServerSocket(portnum); }

catch(Exception err)
{ System.out.println(err); }
}

public void serve()
{
try
{
while(true)
{
Socket client;
client = server.accept();

BufferedReader r;
r = new BufferedReader(new InputStreamReader(client.getInputStream()));

PrintWriter w = new PrintWriter(client.getOutputStream(),true);
w.println("Welcome to Java EchoServer. Type 'bye' to close.");

String line;

do
{
line = r.readLine();

if (line != null)
{ w.println("Got: " + line); }
}
while(!line.trim().equals("bye"));

client.close();
}
}

catch(Exception err)
{ System.err.println(err); }
}

public static void main(String[] args)
{
EchoServer s = new EchoServer(9999);
s.serve();
}

private ServerSocket server;
}

程序在无限循环中不断接受输入,即使我输入“再见”也没有任何反应。我认为主要问题在于 Server.accept() 似乎不起作用。可能出了什么问题?

最佳答案

修改客户端代码

line = r.readLine();

line = con.readLine();

关于JAVA Socket编程死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19999108/

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