简单套接字程序中的错误

发布于 2025-01-06 02:29:27 字数 1246 浏览 2 评论 0原文

我无法在第二个实例上发送数据。服务器只是无限期地等待客户端数据 这是我的示例服务器代码片段:

ServerSocket serv = new ServerSocket(6789);
    Socket soc = serv.accept();
    System.out.println("waiting for client's input");       
    BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
    DataOutputStream out = new DataOutputStream(soc.getOutputStream());
    String indata=in.readLine();
    System.out.println("The client says: "+indata+"\n Send them some data: ");
    String datum="demodata";        
    out.writeBytes(datum);
    System.out.println("Data sent");

示例客户端:

ocket soc = new Socket("localhost",6789);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
    DataOutputStream out = new DataOutputStream(soc.getOutputStream());     
    System.out.println("Connected to: "+soc.getLocalAddress() +"\nEnter data to be sent: ");        
    String outdata = br.readLine(); //take input    
    out.writeBytes(outdata); // send 
    String indata=in.readLine(); //read
    System.out.println("Data Sent! Now reading data from server "+indata)

请告诉我我的问题!提前致谢

I am not able to send the data on the second instance. The server just waits infinitely for client data
Here is my sample server code snippet:

ServerSocket serv = new ServerSocket(6789);
    Socket soc = serv.accept();
    System.out.println("waiting for client's input");       
    BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
    DataOutputStream out = new DataOutputStream(soc.getOutputStream());
    String indata=in.readLine();
    System.out.println("The client says: "+indata+"\n Send them some data: ");
    String datum="demodata";        
    out.writeBytes(datum);
    System.out.println("Data sent");

Sample Client:

ocket soc = new Socket("localhost",6789);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
    DataOutputStream out = new DataOutputStream(soc.getOutputStream());     
    System.out.println("Connected to: "+soc.getLocalAddress() +"\nEnter data to be sent: ");        
    String outdata = br.readLine(); //take input    
    out.writeBytes(outdata); // send 
    String indata=in.readLine(); //read
    System.out.println("Data Sent! Now reading data from server "+indata)

Please tell me my problem! Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

奢欲 2025-01-13 02:29:27

答案很简单。您想要在服务器和客户端之间交换文本行。

正确的部分在服务器端:

String indata=in.readLine();

错误的部分在客户端:

out.writeBytes(outdata); // send 

我还没有测试代码,但看起来你只是发送一些数据,而你的服务器端正在等待 \n (换行转义序列)出现。

选项 1:
构造一个PrintWriter并调用相应的println方法。

选项 2:
手动附加换行符 (\n)。

之后,服务器端的 readLine 将识别以 \n 结尾的行并继续执行。

Answer is quite simple. You want to exchange lines of text between server and client.

The correct part is on the server side:

String indata=in.readLine();

The wrong part is on the client side:

out.writeBytes(outdata); // send 

I haven't tested the code, but it seems you are just sending some data and your server side waits for \n (newline escape sequence) to appear.

Option 1:
Construct a PrintWriter and call the corresponding println method.

Option 2:
Append a newline (\n) manually.

Afterwards, readLine on the server side will recognize the line terminated by \n and will proceed.

回首观望 2025-01-13 02:29:27

我认为您忘记刷新输出流。

在服务器端和客户端的 out.writeBytes() 后面添加一行: out.flush()

I think that you forgot to flush output stream.

Add the line: out.flush() just after out.writeBytes() on both server and client sides.

唯憾梦倾城 2025-01-13 02:29:27

您的客户端不会在其写入的输出中发送换行符。并且您的服务器通过在 BufferedReader 上调用 readLine 隐式地期待这个换行符(它期望通过该方法读取的数据中有一个终止换行符)。调用 out.writeBytes() 后,在客户端和服务器代码中添加以下内容:

out.newLine();
out.flush();

或者,您也可以使用 PrintWriter 的方法,只使用其 println 方法。

Your client is not sending a newline character in the output it is writing. And your server is expecting this newline, implicitly, by calling readLine on BufferedReader (which expects a terminating newline character in the data it reads via that method). Add the following in both your client and server code, after calling out.writeBytes():

out.newLine();
out.flush();

Alternatively, you can use PrintWriter's instead and just utilize its println method.

韶华倾负 2025-01-13 02:29:27

这是一些示例代码。看看它是否适合你。您可以使用 Ctrl-C 停止服务器代码,客户端将等待服务器重新出现。

另外,您可以停止服务器,它将等待客户端重新出现。
main方法有语法

package test;

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

public class SocketIPC{
    public PrintWriter out;
    BufferedReader in;
    Socket socket = null;
    ServerSocket serverSocket = null;
    StringBuffer sb;
    int port;

    public SocketIPC(int port) throws Exception{
        this.port = port;
    }

    public void send(String msg){
        sb.append(msg+"\n");
    }

    public void flush(){
        out.write(sb.toString());
        sb = new StringBuffer();
        out.flush();
    }

    public String recv() throws Exception{
            return in.readLine();
    }

    public void setIO() throws Exception{
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sb = new StringBuffer();
    }

    public void serverLoop() throws Exception{
        serverSocket = new ServerSocket(port);
        while(true){
            socket = serverSocket.accept();
            setIO();

            int count = 0;
            System.out.println("Connected.");
            while(true){
                count += 1;
                for(int j=0; j<100; j++)
                    send("+");
                send(String.format(".%d", count));
                flush();
                Thread.sleep(1000L);
                String msg = recv();
                if (msg!=null)
                    System.out.println(msg);
                else
                    break;// socket connection is broken
            }
            }
    }

    public void clientLoop() throws Exception{
        while(true){
            while(socket==null){
                try{
                    socket = new Socket("localhost", port);
                }catch(Exception e){
                    System.out.println("Waiting for server.");
                    Thread.sleep(1000L);
                }
                }
            setIO();

            System.out.println("Connected.");
            while(true){
                String msg = recv();
                if (msg==null){
                    socket.close();
                    socket = null;
                    break;
                }
                if (msg.charAt(0)=='.'){
                    int idx = Integer.parseInt(msg.substring(1));
                        System.out.println(idx);
                    send(Integer.toString(idx));
                    Thread.sleep(2000);
                    flush();
                }
            }
        }
    }

    public static void main(String[] args){
        if (args.length != 1){
            System.out.println("Server invocation: java test.SocketIPC s");
            System.out.println("Client invocation: java test.SocketIPC c");
        }

        int port = 32000;
        try{
            SocketIPC fip = new SocketIPC(port);
            if (args[0].equals("s")){
                System.out.println("Server started");
                fip.serverLoop();
            }else{
                System.out.println("Client started");
                fip.clientLoop();
            }
            System.out.println("Done");
        }catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
}

Here is some sample code. See if it works for you. You can stop the server code with Ctrl-C and the client will wait for the server to reappear.

Also, you can stop the server and it will wait for the client to reappear.
The main method has syntax

package test;

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

public class SocketIPC{
    public PrintWriter out;
    BufferedReader in;
    Socket socket = null;
    ServerSocket serverSocket = null;
    StringBuffer sb;
    int port;

    public SocketIPC(int port) throws Exception{
        this.port = port;
    }

    public void send(String msg){
        sb.append(msg+"\n");
    }

    public void flush(){
        out.write(sb.toString());
        sb = new StringBuffer();
        out.flush();
    }

    public String recv() throws Exception{
            return in.readLine();
    }

    public void setIO() throws Exception{
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sb = new StringBuffer();
    }

    public void serverLoop() throws Exception{
        serverSocket = new ServerSocket(port);
        while(true){
            socket = serverSocket.accept();
            setIO();

            int count = 0;
            System.out.println("Connected.");
            while(true){
                count += 1;
                for(int j=0; j<100; j++)
                    send("+");
                send(String.format(".%d", count));
                flush();
                Thread.sleep(1000L);
                String msg = recv();
                if (msg!=null)
                    System.out.println(msg);
                else
                    break;// socket connection is broken
            }
            }
    }

    public void clientLoop() throws Exception{
        while(true){
            while(socket==null){
                try{
                    socket = new Socket("localhost", port);
                }catch(Exception e){
                    System.out.println("Waiting for server.");
                    Thread.sleep(1000L);
                }
                }
            setIO();

            System.out.println("Connected.");
            while(true){
                String msg = recv();
                if (msg==null){
                    socket.close();
                    socket = null;
                    break;
                }
                if (msg.charAt(0)=='.'){
                    int idx = Integer.parseInt(msg.substring(1));
                        System.out.println(idx);
                    send(Integer.toString(idx));
                    Thread.sleep(2000);
                    flush();
                }
            }
        }
    }

    public static void main(String[] args){
        if (args.length != 1){
            System.out.println("Server invocation: java test.SocketIPC s");
            System.out.println("Client invocation: java test.SocketIPC c");
        }

        int port = 32000;
        try{
            SocketIPC fip = new SocketIPC(port);
            if (args[0].equals("s")){
                System.out.println("Server started");
                fip.serverLoop();
            }else{
                System.out.println("Client started");
                fip.clientLoop();
            }
            System.out.println("Done");
        }catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文