简体   繁体   English

如何在没有套接字的Android中使用TCP客户端?

[英]How to use TCP Client in Android without Sockets?

I have a TCP server in C# and also a TCP Client in C#, now I need a TCP Client in Android too. 我在C#中有一个TCP服务器,在C#中还有一个TCP客户端,现在我在Android中也需要一个TCP客户端。

All the examples i found are related to sockets, but I'm using a simple TCP Client so they don't work. 我发现的所有示例都与套接字有关,但是我使用的是简单的TCP客户端,因此它们不起作用。

Right now my C# TCP Client is like that: 现在我的C#TCP客户端是这样的:

TcpClient client = new TcpClient("127.0.0.1", 1200);
        NetworkStream n = client.GetStream();
        Console.WriteLine("Insert name");
        string name= Console.ReadLine();
        byte[] message = Encoding.Unicode.GetBytes(name);
        n.Write(message, 0, message.Length);

Is there a corresponding of this function in Android? Android中有此功能的对应项吗?

This is the actual android client i'm trying and that doesn't work 这是我正在尝试的实际android客户端,并且不起作用

InetAddress serverAddr = InetAddress.getByName("127.0.0.1");

        socket = new Socket(serverAddr, 1200);
        EditText et = (EditText) findViewById(R.id.EditText01);
        String str = et.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true);
        out.println(str);

First, this line: 首先,这一行:

InetAddress serverAddr = InetAddress.getByName(127.0.0.1);

contains a syntax error. 包含语法错误。 It should be: 它应该是:

InetAddress serverAddr = InetAddress.getByName("127.0.0.1");

Second, the address "127.0.0.1" refers to the "same machine" that executes the client. 其次,地址“ 127.0.0.1”是指执行客户端的“同一台机器”。 In the case of your C# program, the server runs on the same machine as the client, so it worked. 对于您的C#程序,服务器与客户端在同一台计算机上运行,​​因此可以正常工作。 But in the case of Android, there in no server that runs on the "same machine", which is your Android phone (event if it is emulated, 127.0.0.1 refers to the emulated Android device, not the PC that it works on). 但对于Android,则没有服务器在运行Android手机的“同一台机器”上运行(如果被仿真,则127.0.0.1指的是仿真的Android设备,而不是其工作的PC) 。 You must specify a "good" address to the Android device that refers to the machine on which the server executes. 您必须为Android设备指定一个“良好”地址,该地址引用服务器在其上执行的计算机。

So, the problem is not in using sockets. 因此,问题不在于使用套接字。

您可以简单地使用此线路连接到服务器,如果服务器在PC上运行,也可以尝试禁用防火墙。

Socket server= new Socket("192.168.1.1", 4444); // Enter your PC/Server IP address in place of 192.168.1.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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