我想使用library
我想实现这个功能:
连接到我的 Java 服务器
Socket socket = IO.socket("http://127.0.0.1:4444"); socket.io().open(new Manager.OpenCallback() { @Override public void call(Exception err) { if (err != null) { Log.d("mylog", err.getMessage()); return; } Log.d("mylog", "connected"); } });
发送消息 - 我不明白如何发送消息。
这是我的服务器:
public class Server { public static void main(String[] args) throws IOException { System.out.println("Welcome to Server side"); BufferedReader in = null; PrintWriter out= null; ServerSocket servers = null; Socket fromclient = null; // create server socket try { servers = new ServerSocket(4444); } catch (IOException e) { System.out.println("Couldn't listen to port 4444"); System.exit(-1); } try { System.out.print("Waiting for a client..."); fromclient= servers.accept(); System.out.println("Client connected"); } catch (IOException e) { System.out.println("Can't accept"); System.exit(-1); } in = new BufferedReader(new InputStreamReader(fromclient.getInputStream())); out = new PrintWriter(fromclient.getOutputStream(),true); String input,output; System.out.println("Wait for messages"); while ((input = in.readLine()) != null) { if (input.equalsIgnoreCase("exit")) break; out.println("S ::: "+input); System.out.println(input); } out.close(); in.close(); fromclient.close(); servers.close(); } }
如果我使用 Java 客户端,我可以使用服务器,但我想连接到 Android 客户端。我只找到了这个库,但我不明白它是如何工作的。网站中的示例对我没有帮助。
最佳答案
确保您已在 AndroidManifest.xml 中添加其权限
<uses-permission android:name="android.permission.INTERNET" />
与主线 Linux 内核不同,Android 的内核会限制创建套接字的请求,除非该应用程序已经拥有 INTERNET 权限。
在此 link 中查找有关 Android 偏执网络选项的更多技术信息.
更新#1
如果您想将 Android 客户端连接到 PC 本地主机上的服务器,则不应使用 127.0.0.1
作为服务器 IP 地址。这是 Android 自己的本地主机。您应该使用 10.0.2.2
作为服务器 IP 地址。 More Info
关于java - 我无法使用 Socket.IO-client Java 连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32756696/