套接字编程聊天系统

时间:2016-03-21 10:22:30

标签: php android

我已经使用套接字编程为Android创建了一个聊天系统,当两个或多个设备在同一个WiFi /网络中时,系统工作正常,但是当我关闭WiFi并在一个设备上打开移动数据时该设备没有& #39; t接收消息。有人可以帮我解决这个问题。

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;
    }
}
}

Sever部分

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;

}
}

1 个答案:

答案 0 :(得分:2)

如果使用移动网络的客户端部件必须路由调制解调器,则不能再使用192.168.1.10,否则如果使用移动网络的服务器,则必须更换新的