公共IP上的C#和Android TCP通信

时间:2019-03-03 20:30:09

标签: c# android tcp server

我正在android上编写应用程序,它将通过TCP协议与c#服务器通信。当我使用wi-fi时,我的代码可以正常工作,现在我想更改它,即使android客户端使用移动数据也可以正常工作 C#中的服务器(仅接收和发送数据):

static void Main(string[] args)
    {
        //setup
        Program prog = new Program();//to run non-static void from static context

        //main server 
        try
        {
            IPAddress ipAd = IPAddress.Parse("192.168.x.xxx");
            // Initializes the Listener 
            TcpListener myList = new TcpListener(ipAd, 11000);
            /* Start Listeneting at the specified port */
            myList.Start();

            //label com
            com:
            //accept connection
            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
            //recive data
            byte[] b = new byte[100];
            int k = s.Receive(b);

            char cc = ' ';
            string text = null;//wil produce recived text
            Console.Write("Recieved: ");
            for (int i = 0; i < k - 1; i++)
            {
                Console.Write(Convert.ToChar(b[i]));
                cc = Convert.ToChar(b[i]);
                text += cc.ToString();
            }
            Console.WriteLine();
            //analyze text        
            string reply = prog.analyzeText(text);

            //send reply 
            ASCIIEncoding asen = new ASCIIEncoding();//is using to encode reply<string> to possible to send format 
            s.Send(asen.GetBytes(reply));//send
            s.Close();          

            /* clean up */
            goto com;
            s.Close();
            myList.Stop();
            Console.ReadLine();

        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.StackTrace);
            Console.ReadLine();
        }
    }

和android客户端代码:

private String connectSocket(String msg) {//send and receive data from server
    try {
        InetAddress serverAddr = InetAddress.getByName("192.168.x.xxx");
        Socket socket = new Socket(serverAddr, 11000);
        //define PrintWriter
        PrintWriter out = null;
        try {              
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out.println(msg);
            String text = "";
            String finalText = "";
            while ((text = in.readLine()) != null) {
                finalText += text;
            }
            socket.close();
            return finalText;

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),"Something went wrong.\nTry again in few minutes",Toast.LENGTH_SHORT).show();
            return "exception";
        } finally {
            socket.close();
        }

    } catch (UnknownHostException e) {
        return "UnknownHostException";
    } catch (IOException e) {
        return "IOException";
    }
}

PS。对不起,我的英语,但是我才一年前才开始学习它。

1 个答案:

答案 0 :(得分:0)

无需更改代码。您可能需要正确设置网络,以便测试服务器周围没有防火墙(如果防火墙具有阻止传入连接的防火墙,则可能包括与ISP进行对话)。但是标准的套接字通信可以通过wifi或移动设备进行。