java套接字连接中客户端和服务器之间的数据传输不成功

时间:2014-02-03 19:00:15

标签: java sockets

我使用套接字在java中编写了一个简单的客户端服务器程序。当我在一台机器上运行ServerClas.java而在另一台机器上运行Clientclas.java时,看起来套接字已连接但数据未被传输。我可以告诉他们已连接,因为当Server.java在服务器计算机中终止时,会在客户端捕获异常,说明连接已重置。我无法确定数据未被传输的原因。 请纠正我的错误。

使用netgear路由器连接机器。 java运行时环境是javase1.6

Clientclas.java是

public static void main(String arg[])
{
    Scanner s = new Scanner(System.in);
    System.out.println("Enter your name:");
    name=s.nextLine();
    try {
        InetAddress add = InetAddress.getByName("10.0.0.9");
        Socket sock = new Socket(add,7777);
        OutputStream os = sock.getOutputStream();
        Writer out = new OutputStreamWriter(os);
        out.write("Hai ..!! This is "+name+". Im connected to you");

        InputStream is = sock.getInputStream();
        is = new BufferedInputStream(is);
        int i;
        while((i=is.read())!=-1)
        {
            System.out.write(i);
        }
        sock.close();
        s.close();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        System.out.println("Cannot connect to host");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

ServerClas.java是

public static void main(String arg[])
{
    Scanner s = new Scanner(System.in);
    System.out.println("Enter your name:");
    name = s.nextLine();
    ServerSocket sock;
    try{
        System.out.println("terminating...");
    sock = new ServerSocket(7777);
    System.out.println("Your prog is listening to clients on port 7777 on"+sock.getInetAddress());
    Socket soc = sock.accept();

    InputStream is = soc.getInputStream();
    is = new BufferedInputStream(is);
    int i;
    while((i=is.read())!=-1)
    {
        System.out.write(i);
    }
    System.out.println("Data recieved");

    OutputStream os = soc.getOutputStream();
    Writer out = new OutputStreamWriter(os);
    out.write("Hai ..!! This is "+ServerClas.name+". Im connected to you");
    out.flush();        }
    catch(IOException e)
    {
        System.out.println("Excption caught");
        e.printStackTrace();
    }
    s.close();
}

1 个答案:

答案 0 :(得分:1)

当您从输入流中读取数据时,您会一直读到它,直到它关闭为止,但是在收到回复之后才会关闭连接,直到您关闭连接才会收到回复。

即。你有一个僵局。

您需要某种方式知道邮件何时发送,而连接仍处于打开状态,以便您可以发送回复。我建议您在行尾添加\n,并在看到此内容时停止阅读。