IT序号网

JAVA Socket编程死循环

third_qq_acbf90bbd2dede1d 2023年09月15日 程序员 7 0

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

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(); 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!