简体   繁体   English

在Android设备和PC之间使用套接字(同一网络)

[英]Using sockets between android device and pc (same network)

I have been struggling with this for a while now. 我一直在努力解决这个问题。 What I'm simply trying to do, is to create a socket connection between my android app and my java program on PC. 我只是想做的是在我的Android应用程序和我的PC上的java程序之间创建一个套接字连接。

I have both tried UDP and TCP sockets and different kinds of IP's and port numbers. 我已经尝试过UDP和TCP套接字以及不同类型的IP和端口号。

So, how can I achieve this? 那么,我怎样才能做到这一点?

Here is my (current code) with a (attempted) TCP connection: 这是我的(当前代码)与(尝试)TCP连接:

Code snip from the server side (PC java program): 来自服务器端的代码片段(PC java程序):

try {

    DatagramSocket socket = new DatagramSocket(4466);
    byte[] buffer = new byte[2048];

    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    socket.receive(packet);

} catch (SocketException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

And the relevant snip from my android app (client): 以及来自我的Android应用程序(客户端)的相关剪辑:

try {

    InetAddress host = InetAddress.getByName("192.168.1.255");
    DatagramSocket socket = new DatagramSocket (null);
    byte[] buffer = new byte[2048];
    buffer = "hej hej".getBytes();

    DatagramPacket packet=new DatagramPacket (buffer, buffer.length, host, 4466);
    socket.send(packet);
    socket.close();

} catch(Exception e) {
    e.printStackTrace();
}

The IP address: 192.168.1.255 is supposed to be some kind of broadcast IP. IP地址:192.168.1.255应该是某种广播IP。 But I have also tried different IP's like the IP for my PC (hard-coded in the android app), the 255.255.255.0, localhost and so on. 但我也尝试过不同的IP,例如我的PC的IP(在Android应用程序中硬编码),255.255.255.0,localhost等等。

I would really appreciate it if anyone could help me out! 如果有人能帮助我,我真的很感激!

I just created simple demo in Android and Desktop application which is connected via Socket Connection and its like a Chat Application. 我刚刚在Android和桌面应用程序中创建了简单的演示,它通过Socket Connection连接,就像聊天应用程序一样。 Might be that will help you a lot. 可能会对你有很大的帮助。 Please check below link for more clarification. 请查看以下链接以获得更多说明。

Android Client Connected with Socket Android客户端与Socket连接

You need the public address of your computer (search for something like what's my IP) and make sure there's no firewall blocking the port. 您需要计算机的公共地址(搜索类似我的IP的内容)并确保没有防火墙阻止该端口。 The 192.168.***.* address is not public (it's a LAN address), and the emulator (or an actual phone) won't able to see it. 192.168。***。*地址不是公共的(它是LAN地址),模拟器(或实际的电话)将无法看到它。

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

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