Php Socket编程聊天系统

Php Socket编程聊天系统,php,android,Php,Android,我使用socket编程为android创建了一个聊天系统,当两台或更多设备位于同一WiFi/网络中时,该系统工作正常,但当我关闭WiFi并在一台设备上打开移动数据时,该设备不会接收消息。有人能帮我解决这个问题吗 static final int SocketServerPORT = 8181; LinearLayout loginPanel, chatPanel; Button buttonSend; String msgLog = ""; ChatClientThread chatClien

我使用socket编程为android创建了一个聊天系统,当两台或更多设备位于同一WiFi/网络中时,该系统工作正常,但当我关闭WiFi并在一台设备上打开移动数据时,该设备不会接收消息。有人能帮我解决这个问题吗

static final int SocketServerPORT = 8181;
LinearLayout loginPanel, chatPanel;

Button buttonSend;
String msgLog = "";
ChatClientThread chatClientThread = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cliyent);


    loginPanel = (LinearLayout)findViewById(R.id.loginpanel);
    chatPanel = (LinearLayout)findViewById(R.id.chatpanel);



    buttonSend = (Button)findViewById(R.id.send);

    buttonSend.setOnClickListener(buttonSendOnClickListener);
}



OnClickListener buttonSendOnClickListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        String ip ="192.168.1.10";
        chatClientThread = new ChatClientThread("Dhanushka", ip, SocketServerPORT);
        chatClientThread.start();


        System.out.println("plz givme curent location");
        chatClientThread.sendMsg("plz givme curent location " + "\n");

    }

};



private class ChatClientThread extends Thread {

    String name;
    String dstAddress;
    int dstPort;

    String msgToSend = "";
    boolean goOut = false;

    ChatClientThread(String name, String address, int port) {
        this.name = name;
        dstAddress = address;
        dstPort = port;
    }

    @Override
    public void run() {
        Socket socket = null;
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;

        try {
            socket = new Socket(dstAddress, dstPort);
            dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());
            dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream.writeUTF(name);
            dataOutputStream.flush();

            while (!goOut) {
                if (dataInputStream.available() > 0) {
                    msgLog += dataInputStream.readUTF();

                    Cliyent.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            System.out.println("msgLog"+msgLog);
                        }
                    });
                }

                if(!msgToSend.equals("")){
                    dataOutputStream.writeUTF(msgToSend);
                    dataOutputStream.flush();
                    msgToSend = "";
                }
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
            final String eString = e.toString();
            Cliyent.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(Cliyent.this, eString, Toast.LENGTH_LONG).show();
                }

            });
        } catch (IOException e) {
            e.printStackTrace();
            final String eString = e.toString();
            Cliyent.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(Cliyent.this, eString, Toast.LENGTH_LONG).show();
                }

            });
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            Cliyent.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {

                }

            });
        }

    }

    private void sendMsg(String msg){
        msgToSend = msg;
    }
}
}

断绝

public class MainActivity extends ActionBarActivity {

static final int SocketServerPORT = 8080;

TextView infoIp, infoPort, chatMsg;

String msgLog = "";

List<ChatClient> userList;

ServerSocket serverSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    infoIp = (TextView) findViewById(R.id.infoip);
    infoPort = (TextView) findViewById(R.id.infoport);
    chatMsg = (TextView) findViewById(R.id.chatmsg);

    infoIp.setText(getIpAddress());

    userList = new ArrayList<ChatClient>();

    ChatServerThread chatServerThread = new ChatServerThread();
    chatServerThread.start();
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (serverSocket != null) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private class ChatServerThread extends Thread {

    @Override
    public void run() {
        Socket socket = null;

        try {
            serverSocket = new ServerSocket(SocketServerPORT);
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    infoPort.setText("I'm waiting here: "
                            + serverSocket.getLocalPort());
                }
            });

            while (true) {
                socket = serverSocket.accept();
                ChatClient client = new ChatClient();
                userList.add(client);
                ConnectThread connectThread = new ConnectThread(client, socket);
                connectThread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

private class ConnectThread extends Thread {

    Socket socket;
    ChatClient connectClient;
    String msgToSend = "";

    ConnectThread(ChatClient client, Socket socket){
        connectClient = client;
        this.socket= socket;
        client.socket = socket;
        client.chatThread = this;
    }

    @Override
    public void run() {
        DataInputStream dataInputStream = null;
        DataOutputStream dataOutputStream = null;

        try {
            dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream = new DataOutputStream(socket.getOutputStream());

            String n = dataInputStream.readUTF();

            connectClient.name = n;

            msgLog += connectClient.name + " connected@" + connectClient.socket.getInetAddress() + ":" + connectClient.socket.getPort() + "\n";
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                  //  chatMsg.setText(msgLog);

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

                    // set title
                    alertDialogBuilder.setTitle(msgLog);

                    // set dialog message
                    alertDialogBuilder
                            .setMessage(msgLog)
                            .setCancelable(false)
                            .setPositiveButton("Available",new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,int id) {



                                }
                            })
                            .setNegativeButton("Curent Location",new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,int id) {

                                    dialog.cancel();
                                }
                            });


                    AlertDialog alertDialog = alertDialogBuilder.create();


                    alertDialog.show();
                }
            });

            dataOutputStream.writeUTF("Welcome " + n + "\n");
            dataOutputStream.flush();

            broadcastMsg(n + " join our chat.\n");

            while (true) {
                if (dataInputStream.available() > 0) {
                    String newMsg = dataInputStream.readUTF();


                    msgLog += n + ": " + newMsg;
                    MainActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            chatMsg.setText(msgLog);
                        }
                    });

                    broadcastMsg(n + ": " + newMsg);
                }

                if(!msgToSend.equals("")){
                    dataOutputStream.writeUTF(msgToSend);
                    dataOutputStream.flush();
                    msgToSend = "";
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            userList.remove(connectClient);
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,
                            connectClient.name + " removed.", Toast.LENGTH_LONG).show();

                    msgLog += "-- " + connectClient.name + " leaved\n";
                    MainActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            chatMsg.setText(msgLog);
                        }
                    });

                    broadcastMsg("-- " + connectClient.name + " leaved\n");
                }
            });
        }

    }

    private void sendMsg(String msg){
        msgToSend = msg;
    }

}

private void broadcastMsg(String msg){
    for(int i=0; i<userList.size(); i++){
        userList.get(i).chatThread.sendMsg(msg);
        msgLog += "- send to " + userList.get(i).name + "\n";
    }

    MainActivity.this.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            chatMsg.setText(msgLog);
        }
    });
}

private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += "SiteLocalAddress: "
                            + inetAddress.getHostAddress() + "\n";
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
}

class ChatClient {
    String name;
    Socket socket;
    ConnectThread chatThread;

}
}
公共类MainActivity扩展了ActionBarActivity{
静态最终int SocketServerPORT=8080;
TextView infoIp、infoPort、chatMsg;
字符串msgLog=“”;
列表用户列表;
服务器套接字服务器套接字;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp=(TextView)findViewById(R.id.infoIp);
infoPort=(TextView)findViewById(R.id.infoPort);
chatMsg=(TextView)findViewById(R.id.chatMsg);
infoIp.setText(getIpAddress());
userList=newarraylist();
ChatServerThread ChatServerThread=新的ChatServerThread();
chatServerThread.start();
}
@凌驾
受保护的空onDestroy(){
super.ondestory();
if(serverSocket!=null){
试一试{
serverSocket.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
私有类ChatServerThread扩展线程{
@凌驾
公开募捐{
套接字=空;
试一试{
serverSocket=新的serverSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
infoPort.setText(“我在这里等待:”
+serverSocket.getLocalPort());
}
});
while(true){
socket=serverSocket.accept();
ChatClient=new ChatClient();
添加(客户端);
ConnectThread ConnectThread=新的ConnectThread(客户端、套接字);
connectThread.start();
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(套接字!=null){
试一试{
socket.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
}
}
私有类ConnectThread扩展线程{
插座;
聊天客户端连接客户端;
字符串msgToSend=“”;
ConnectThread(聊天客户端、套接字){
connectClient=client;
这个.socket=socket;
client.socket=socket;
client.chatThread=this;
}
@凌驾
公开募捐{
DataInputStream DataInputStream=null;
DataOutputStream DataOutputStream=null;
试一试{
dataInputStream=新的dataInputStream(socket.getInputStream());
dataOutputStream=新的dataOutputStream(socket.getOutputStream());
字符串n=dataInputStream.readUTF();
connectClient.name=n;
msgLog+=connectClient.name+“connected@”+connectClient.socket.getInetAddress()+”:“+connectClient.socket.getPort()+”\n”;
MainActivity.this.runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
//chatMsg.setText(msgLog);
AlertDialog.Builder alertDialogBuilder=新建AlertDialog.Builder(MainActivity.this);
//定名
alertDialogBuilder.setTitle(msgLog);
//设置对话框消息
alertDialogBuilder
.setMessage(msgLog)
.setCancelable(错误)
.setPositiveButton(“可用”,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
}
})
.setNegativeButton(“当前位置”,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
dialog.cancel();
}
});
AlertDialog AlertDialog=alertDialogBuilder.create();
alertDialog.show();
}
});
dataOutputStream.writeUTF(“欢迎”+n+“\n”);
dataOutputStream.flush();
broadcastMsg(n+“加入我们的聊天。\n”);
while(true){
if(dataInputStream.available()>0){
字符串newMsg=dataInputStream.readUTF();
msgLog+=n+“:”+newMsg;
MainActivity.this.runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
chatMsg.setText(msgLog);
}
});
广播消息(n+“:”+newMsg);
}
如果(!msgToSend.equals(“”){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend=“”;
}
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(dataInputStream!=null){
试一试{
dataInputStream.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
如果(dataOutputStream!=null){
试一试{
dataOutputStream.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块