Simple Socket程序出错

时间:2012-02-16 16:57:55

标签: java sockets java-io

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

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)

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

4 个答案:

答案 0 :(得分:1)

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

在服务器端和客户端out.flush()之后添加行out.writeBytes()

答案 1 :(得分:1)

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

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

或者,您可以改为使用PrintWriter,只使用其println方法。

答案 2 :(得分:1)

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

正确的部分在服务器端:

String indata=in.readLine();

错误的部分在客户端:

out.writeBytes(outdata); // send 

我没有测试过代码,但似乎你只是发送了一些数据而服务器端等待出现\n(换行符转义序列)。

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

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

之后,服务器端的readLine将识别由\n终止的行,并将继续。

答案 3 :(得分:1)

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

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

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