0

I tried this code from this site server client code

It worked perfect on my machine,I first ran the server code then the client code. And I got the time. I tried putting the server side code on to another PC and running it on eclipse there,similarly I tried running client side code from eclipse on my side but wasn't successful. It gave me the following error:

Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
    at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.net.PlainSocketImpl.bind(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at sample.servertime.main(servertime.java:13)

Am I doing it correct or is it wrong what I am doing.Need help. Here are the 2 codes.

// Date Client   

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

class DateClient
{
    publicstaticvoid main(String args[]) throws Exception
    {
        Socket soc=new Socket(InetAddress.getLocalHost(),5217);        
        BufferedReader in=new BufferedReader(
                new InputStreamReader(
                        soc.getInputStream()
                        )
                    );

        System.out.println(in.readLine());
    }    
}



// Date Server

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

class DateServer
{
    publicstaticvoid main(String args[]) throws Exception
    {
        InetAddress locIP = InetAddress.getByName("192.168.1.21");
        ServerSocket s= new ServerSocket(5217, 0, locIP);

        while(true)
        {
            System.out.println("Waiting For Connection ...");
            Socket soc=s.accept();
            DataOutputStream out=new DataOutputStream(soc.getOutputStream());
            out.writeBytes("Server Date" + (new Date()).toString() + "\n");
            out.close();
            soc.close();
        }

    }
}
4

1 回答 1

1

In the server part you've hard coded the ip address for the server:

InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);

When you run it on the other machine the address will be different and therefore it can't be bound unless you change it.
You could change it to bind to all addresses like:

ServerSocket s = new ServerSocket(5217);

Also, the client will always try to connect to the local machine:

Socket soc=new Socket(InetAddress.getLocalHost(),5217);

So if you want to have the client connect to a server on another machine InetAddress.getLocalHost()has to be changed to the address of the server.

于 2013-11-09T10:57:08.317 回答