套接字编程(Socket)

作者:追风剑情 发布于:2015-10-16 21:49 分类:Android

聊天程序客户端示例

一、在AndroidManifest.xml中配置权限

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

二、创建负责读取消息的线程类

package com.example.androidtest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.util.Log;

public class CommsThread extends Thread {

	private final Socket socket;
	private final InputStream inputStream;
	private final OutputStream outputStream;
	
	public CommsThread(Socket sock)
	{
		socket = sock;
		InputStream tmpIn = null;
		OutputStream tmpOut = null;
		try {
			tmpIn = socket.getInputStream();
			tmpOut = socket.getOutputStream();
		} catch (IOException e) {
			Log.d("AndroidTest", e.getLocalizedMessage());
		}
		inputStream = tmpIn;
		outputStream = tmpOut;
	}
	
	public void run()
	{
		byte[] buffer = new byte[1024];
		int bytes;
		while (true) {
			try {
				bytes = inputStream.read(buffer);
				
			} catch (IOException e) {
				break;
			}
		}
	}
	
	public void write(byte[] bytes)
	{
		try {
			outputStream.write(bytes);
		} catch (IOException e) {}
	}
	
	public void canncel()
	{
		try {
			socket.close();
		} catch (IOException e) {}
	}
}

三、创建活动

视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <EditText 
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send Message"
        android:onClick="onClickSend"/>
    
    <TextView
        android:id="@+id/txtMessagesReceived"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:scrollbars="vertical" />

</LinearLayout>

代码

package com.example.androidtest;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class SocketsActivity extends Activity {

	static final String NICKNAME = "Wei-Meng";
	InetAddress serverAddress;
	Socket socket;
	
	static TextView txtMessagesReceived;
	EditText txtMessage;
	
	CommsThread commsThread;
	
	static Handler UIupdater = new Handler(){
		@Override
		public void handleMessage(Message msg)
		{
			int numOfBytesReceived = msg.arg1;
			byte[] buffer = (byte[]) msg.obj;
			String strReceived = new String(buffer);
			strReceived = strReceived.substring(0, numOfBytesReceived);
			txtMessagesReceived.setText(txtMessagesReceived.getText().toString() + strReceived);
		}
	};
	
	private class CreateCommThreadTask extends AsyncTask<Void, Integer, Void>
	{
		@Override
		protected Void doInBackground(Void... params)
		{
			try {
				serverAddress = InetAddress.getByName("192.168.1.142");
				socket = new Socket(serverAddress, 500);
				commsThread = new CommsThread(socket);
				commsThread.start();
				sendToServer(NICKNAME);
			} catch (UnknownHostException e) {
				Log.d("AndroidTest", e.getLocalizedMessage());
			} catch (IOException e) {
				Log.d("AndroidTest", e.getLocalizedMessage());
			}
			return null;
		}
	}
	
	private class WriteToServerTask extends AsyncTask<byte[], Void, Void>
	{
		@Override
		protected Void doInBackground(byte[]... data)
		{
			commsThread.write(data[0]);
			return null;
		}
	}
	
	private class CloseSocketTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... params)
		{
			try {
				socket.close();
			} catch (IOException e) {
				Log.d("AndroidTest", e.getLocalizedMessage());
			}
			return null;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sockets);
		
		txtMessage = (EditText) findViewById(R.id.txtMessage);
		txtMessagesReceived = (TextView) findViewById(R.id.txtMessagesReceived);
	}
	
	public void onClickSend(View view) {
		sendToServer(txtMessage.getText().toString());
	}
	
	private void sendToServer(String message)
	{
		byte[] theByteArray = message.getBytes();
		new WriteToServerTask().execute(theByteArray);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		new CreateCommThreadTask().execute();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		new CloseSocketTask().execute();
	}
}

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号