简体   繁体   中英

Problems with connection between PC and Android device - SocketException

When i tryed to connect from PC to android device, i caught a socket exception "No Connection could be made because the target machine actively refused it". Code of a server at android device:

private void networkOperations()
{
    Thread networkThread = new Thread (null, doBackgroundThreadProcessing, "Network");
    networkThread.start();
}

private Runnable doBackgroundThreadProcessing = new Runnable() 
{
    public void run() {
        backgroundThreadProcessing();
    }
};

private void backgroundThreadProcessing()
{
    Socket s = null;
    ServerSocket ss = null;
    try {
        ss = new ServerSocket(8867);
    } catch (IOException e) {
        e.printStackTrace();
    }
    while(!Thread.currentThread().isInterrupted())
    {
        try {
            if (s == null)
                s = ss.accept();
            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String st = null;
            st = input.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

networkOperations() is calling in the onCreate() method of the Main Activity. Code of a client at PC(C#):

class Connection
{
    public Connection(String ip, String port)
    {
        Ip = IPAddress.Parse(ip);
        Port = Convert.ToInt32(port);
    }

    public IPAddress Ip
    {
        get;
        set;
    }

    public Int32 Port
    {
        get;
        set;
    }

    public Boolean ConnectionError;

    public Socket S;

    public void ConnectToServer()
    {
        IPEndPoint ipe = new IPEndPoint(Ip, Port);
        S = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            S.Connect(ipe);
        }
        catch (SocketException e)
        {
        }
    }

Can anyone help me with this problem please? Thanks.

Based on the comments, there are two things you should pay attention. First, you are contacting a device in your local network from your local network using the public address. I'm not sure that all of the routers will be able to do this properly, but nevertheless you need to forward the 8867 port if you want public access. Try it, it may help.

Search your router here and you will find an explanation how to do that: http://portforward.com/

The phone should certainly be available when accessing the phone from outside the network after forwarding. Of course, your phone should always have the same local address. Reserve it in the router settings or set it manually on the phone.

For testing purposes, try to use the phones local IP address from your PC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM