本文主要是介绍使用Socket实现安卓中IPC,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。
建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API),对TCP/IP的封装,TCP/IP也要提供可供程序员做网络开发所用的接口,这就是Socket编程接口;HTTP是轿车,提供了封装或者显示数据的具体形式;Socket是发动机,提供了网络通信的能力。
Socket的英文原义是“孔”或“插座”。作为BSD UNIX的进程通信机制,取后一种意思。通常也称作”套接字”,用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。Socket正如其英文原意那样,像一个多孔插座。一台主机犹如布满各种插座的房间,每个插座有一个编号,有的插座提供220伏交流电, 有的提供110伏交流电,有的则提供有线电视节目。 客户软件将插头插到不同编号的插座,就可以得到不同的服务。
在Android中使用Socket实现聊天室功能
public class TCPClientActivity extends Activity implements OnClickListener {private static final int MESSAGE_RECEIVE_NEW_MSG = 1;private static final int MESSAGE_SOCKET_CONNECTED = 2;private Button mSendButton;private TextView mMessageTextView;private EditText mMessageEditText;private PrintWriter mPrintWriter;private Socket mClientSocket;@SuppressLint("HandlerLeak")private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case MESSAGE_RECEIVE_NEW_MSG: {mMessageTextView.setText(mMessageTextView.getText()+ (String) msg.obj);break;}case MESSAGE_SOCKET_CONNECTED: {mSendButton.setEnabled(true);break;}default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tcpclient);mMessageTextView = (TextView) findViewById(R.id.msg_container);mSendButton = (Button) findViewById(R.id.send);mSendButton.setOnClickListener(this);mMessageEditText = (EditText) findViewById(R.id.msg);Intent service = new Intent(this, TCPServerService.class);startService(service);new Thread() {@Overridepublic void run() {connectTCPServer();}}.start();}@Overrideprotected void onDestroy() {if (mClientSocket != null) {try {mClientSocket.shutdownInput();mClientSocket.close();} catch (IOException e) {e.printStackTrace();}}super.onDestroy();}@Overridepublic void onClick(View v) {if (v == mSendButton) {final String msg = mMessageEditText.getText().toString();if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {mPrintWriter.println(msg);mMessageEditText.setText("");String time = formatDateTime(System.currentTimeMillis());final String showedMsg = "self " + time + ":" + msg + "\n";mMessageTextView.setText(mMessageTextView.getText() + showedMsg);}}}@SuppressLint("SimpleDateFormat")private String formatDateTime(long time) {return new SimpleDateFormat("(HH:mm:ss)").format(new Date(time));}private void connectTCPServer() {Socket socket = null;while (socket == null) {try {socket = new Socket("localhost", 8688);mClientSocket = socket;mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED);System.out.println("connect server success");} catch (IOException e) {SystemClock.sleep(1000);System.out.println("connect tcp server failed, retry...");}}try {// 接收服务器端的消息BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));while (!TCPClientActivity.this.isFinishing()) {String msg = br.readLine();System.out.println("receive :" + msg);if (msg != null) {String time = formatDateTime(System.currentTimeMillis());final String showedMsg = "server " + time + ":" + msg+ "\n";mHandler.obtainMessage(MESSAGE_RECEIVE_NEW_MSG, showedMsg).sendToTarget();}}System.out.println("quit...");MyUtils.close(mPrintWriter);MyUtils.close(br);socket.close();} catch (IOException e) {e.printStackTrace();}}
}
布局文件 activity_tcpclient.xml
public class TCPServerService extends Service {private boolean mIsServiceDestoryed = false;private String[] mDefinedMessages = new String[] {"你好啊,哈哈","请问你叫什么名字呀?","今天北京天气不错啊,shy","你知道吗?我可是可以和多个人同时聊天的哦","给你讲个笑话吧:据说爱笑的人运气不会太差,不知道真假。"};@Overridepublic void onCreate() {new Thread(new TcpServer()).start();super.onCreate();}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onDestroy() {mIsServiceDestoryed = true;super.onDestroy();}private class TcpServer implements Runnable {@SuppressWarnings("resource")@Overridepublic void run() {ServerSocket serverSocket = null;try {serverSocket = new ServerSocket(8688);} catch (IOException e) {System.err.println("establish tcp server failed, port:8688");e.printStackTrace();return;}while (!mIsServiceDestoryed) {try {// 接受客户端请求final Socket client = serverSocket.accept();System.out.println("accept");new Thread() {@Overridepublic void run() {try {responseClient(client);} catch (IOException e) {e.printStackTrace();}};}.start();} catch (IOException e) {e.printStackTrace();}}}}private void responseClient(Socket client) throws IOException {// 用于接收客户端消息BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));// 用于向客户端发送消息PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);out.println("欢迎来到聊天室!");while (!mIsServiceDestoryed) {String str = in.readLine();System.out.println("msg from client:" + str);if (str == null) {break;}int i = new Random().nextInt(mDefinedMessages.length);String msg = mDefinedMessages[i];out.println(msg);System.out.println("send :" + msg);}System.out.println("client quit.");// 关闭流MyUtils.close(out);MyUtils.close(in);client.close();}}
这篇关于使用Socket实现安卓中IPC的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!