简体   繁体   English

Android应用程序通过套接字与服务器通信

[英]Android app communicating with server via sockets

Im making an Android app that communicates with a server. 我正在制作一个与服务器通信的Android应用。 When the Android-phone receives a SMS I want it to send it thru a socket to my server. 当Android手机收到短信时,我希望它通过套接字将其发送到我的服务器。

public class Server { 公共类服务器{

public static final int PORT = 8080;
public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    try {
        Socket socket = s.accept();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str = in.readLine();
            System.out.println(str);
        } 
        finally {
            socket.close();
        }
    } 
    finally {
        s.close();
    }
} 

} }

This is my client: 这是我的客户:

public Client(String message){

    try {
        Socket socket = new Socket("127.0.0.1", 8080);
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        out.println(message);
        socket.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

Im not getting any connection when Im calling the Client class from the android app. 我从android应用程序调用Client类时,我没有任何连接。 Anyone know how to fix this problem? 有人知道如何解决此问题吗?

The class 'Client' is called from the onReceive(Context context, Intent intent){ method when a message is received on the phone. 当在电话上收到消息时,从onReceive(Context context,Intent intent){方法调用类'Client'。

Your Android Client is trying to create a socket connecting to the IP 127.0.0.1 which is the loopback address. 您的Android客户端正在尝试创建一个连接到IP 127.0.0.1(即回送地址)的套接字。 You are essentially trying to connect to yourself 您实质上是在尝试与自己建立联系

Change 更改

Socket socket = new Socket("127.0.0.1", 8080);

to

Socket socket = new Socket("your server's IP", 8080);

Please don't literally change it to "your server's IP" :) make it 192.168.1.104 or whatever the servers address is on the network. 请不要从字面上将其更改为“您的服务器的IP” :)将其设置为192.168.1.104或网络上的任何服务器地址。

我解决了,忘了将此添加到我的androidmanifest.xlm

< uses-permission android:name="android.permission.INTERNET">< /uses-permission>

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

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