Android Socket网络通信

1.服务器程序:

Java代码 复制代码  收藏代码
  1. package com;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.BufferedWriter;   
  5. import java.io.IOException;   
  6. import java.io.InputStreamReader;   
  7. import java.io.OutputStreamWriter;   
  8. import java.io.PrintWriter;   
  9. import java.net.ServerSocket;   
  10. import java.net.Socket;   
  11. import java.util.ArrayList;   
  12. import java.util.List;   
  13. import java.util.concurrent.ExecutorService;   
  14. import java.util.concurrent.Executors;   
  15.   
  16. /**  
  17.  * com Server  
  18.  *   
  19.  * @author Aina.huang E-mail: 674023920@qq.com  
  20.  * @version 创建时间:2010 Jul 14, 2010 10:45:35 AM 类说明  
  21.  */  
  22. public class Main {   
  23.   
  24.     private static final int PORT = 9999;// 端口监听   
  25.     private List<Socket> mList = new ArrayList<Socket>();// 存放客户端socket   
  26.     private ServerSocket server = null;   
  27.     private ExecutorService mExecutorService = null;// 线程池   
  28.   
  29.     /**  
  30.      * @param args  
  31.      */  
  32.     public static void main(String[] args) {   
  33.         // TODO Auto-generated method stub   
  34.         new Main();   
  35.     }   
  36.   
  37.     public Main() {   
  38.         try {   
  39.             server = new ServerSocket(PORT);   
  40.             mExecutorService = Executors.newCachedThreadPool();// 创建一个线程池   
  41.             System.out.println("Server Start...");   
  42.             Socket client = null;   
  43.             while (true) {   
  44.                 client = server.accept();   
  45.                 mList.add(client);   
  46.                 mExecutorService.execute(new Service(client));// 开启一个客户端线程.   
  47.             }   
  48.         } catch (Exception ex) {   
  49.             ex.printStackTrace();   
  50.         }   
  51.     }   
  52.   
  53.     public class Service implements Runnable {   
  54.   
  55.         private Socket socket;   
  56.         private BufferedReader in = null;   
  57.         private String msg = "";   
  58.   
  59.         public Service(Socket socket) {   
  60.             this.socket = socket;   
  61.             try {   
  62.                 in = new BufferedReader(new InputStreamReader(socket   
  63.                         .getInputStream()));   
  64.                 msg = "user:" + this.socket.getInetAddress() + " come total:"  
  65.                         + mList.size();   
  66.                 this.sendmsg();   
  67.             } catch (IOException e) {   
  68.                 e.printStackTrace();   
  69.             }   
  70.         }   
  71.   
  72.         public void run() {   
  73.             // TODO Auto-generated method stub   
  74.             try {   
  75.                 while (true) {   
  76.                     if ((msg = in.readLine()) != null) {   
  77.                         if (msg.equals("exit")) {   
  78.                             System.out.println("sssssssssss");   
  79.                             mList.remove(socket);   
  80.                             in.close();   
  81.                             msg = "user:" + socket.getInetAddress()   
  82.                                     + " exit total:" + mList.size();   
  83.                             socket.close();   
  84.                             this.sendmsg();   
  85.                             break;   
  86.                         } else {   
  87.                             msg = socket.getInetAddress() + " : " + msg;   
  88.                             this.sendmsg();   
  89.                         }   
  90.                     }   
  91.   
  92.                 }   
  93.             } catch (Exception ex) {   
  94.                 System.out.println("server 读取数据异常");   
  95.                 ex.printStackTrace();   
  96.             }   
  97.         }   
  98.   
  99.         /**  
  100.          * 发送消息给所有客户端  
  101.          */  
  102.         public void sendmsg() {   
  103.             System.out.println(msg);   
  104.             int num = mList.size();   
  105.             for (int i = 0; i < num; i++) {   
  106.                 Socket mSocket = mList.get(i);   
  107.                 PrintWriter pout = null;   
  108.                 try {   
  109.                     pout = new PrintWriter(new BufferedWriter(   
  110.                             new OutputStreamWriter(mSocket.getOutputStream())),   
  111.                             true);   
  112.                     pout.println(msg);   
  113.                 } catch (IOException e) {   
  114.                     e.printStackTrace();   
  115.                 }   
  116.             }   
  117.         }   
  118.     }   
  119. }  
package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * com Server
 * 
 * @author Aina.huang E-mail: 674023920@qq.com
 * @version 创建时间:2010 Jul 14, 2010 10:45:35 AM 类说明
 */
public class Main {

	private static final int PORT = 9999;// 端口监听
	private List<Socket> mList = new ArrayList<Socket>();// 存放客户端socket
	private ServerSocket server = null;
	private ExecutorService mExecutorService = null;// 线程池

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Main();
	}

	public Main() {
		try {
			server = new ServerSocket(PORT);
			mExecutorService = Executors.newCachedThreadPool();// 创建一个线程池
			System.out.println("Server Start...");
			Socket client = null;
			while (true) {
				client = server.accept();
				mList.add(client);
				mExecutorService.execute(new Service(client));// 开启一个客户端线程.
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public class Service implements Runnable {

		private Socket socket;
		private BufferedReader in = null;
		private String msg = "";

		public Service(Socket socket) {
			this.socket = socket;
			try {
				in = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));
				msg = "user:" + this.socket.getInetAddress() + " come total:"
						+ mList.size();
				this.sendmsg();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			// TODO Auto-generated method stub
			try {
				while (true) {
					if ((msg = in.readLine()) != null) {
						if (msg.equals("exit")) {
							System.out.println("sssssssssss");
							mList.remove(socket);
							in.close();
							msg = "user:" + socket.getInetAddress()
									+ " exit total:" + mList.size();
							socket.close();
							this.sendmsg();
							break;
						} else {
							msg = socket.getInetAddress() + " : " + msg;
							this.sendmsg();
						}
					}

				}
			} catch (Exception ex) {
				System.out.println("server 读取数据异常");
				ex.printStackTrace();
			}
		}

		/**
		 * 发送消息给所有客户端
		 */
		public void sendmsg() {
			System.out.println(msg);
			int num = mList.size();
			for (int i = 0; i < num; i++) {
				Socket mSocket = mList.get(i);
				PrintWriter pout = null;
				try {
					pout = new PrintWriter(new BufferedWriter(
							new OutputStreamWriter(mSocket.getOutputStream())),
							true);
					pout.println(msg);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}



2.客户端程序:

Java代码 复制代码  收藏代码
  1. package com.Aina.Android;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.BufferedWriter;   
  5. import java.io.InputStreamReader;   
  6. import java.io.OutputStreamWriter;   
  7. import java.io.PrintWriter;   
  8. import java.net.Socket;   
  9.   
  10. import android.app.Activity;   
  11. import android.app.AlertDialog;   
  12. import android.content.DialogInterface;   
  13. import android.os.Bundle;   
  14. import android.os.Handler;   
  15. import android.os.Message;   
  16. import android.util.Log;   
  17. import android.view.View;   
  18. import android.widget.Button;   
  19. import android.widget.EditText;   
  20. import android.widget.TextView;   
  21.   
  22. public class Test extends Activity implements Runnable {   
  23.     /** Called when the activity is first created. */  
  24.     private TextView tv_msg = null;   
  25.     private EditText ed_msg = null;   
  26.     private Button btn_send = null;   
  27.     private Button btn_login = null;   
  28.     private static final String HOST = "192.168.0.132";   
  29.     private static final int PORT = 9999;   
  30.     private Socket socket = null;   
  31.     private BufferedReader in = null;   
  32.     private PrintWriter out = null;   
  33.     private String content = "";   
  34.   
  35.     @Override  
  36.     public void onCreate(Bundle savedInstanceState) {   
  37.         super.onCreate(savedInstanceState);   
  38.         setContentView(R.layout.main);   
  39.         tv_msg = (TextView) this.findViewById(R.id.TextView);   
  40.         ed_msg = (EditText) this.findViewById(R.id.EditText01);   
  41.         btn_login = (Button) this.findViewById(R.id.Button01);   
  42.         btn_send = (Button) this.findViewById(R.id.Button02);   
  43.         try {   
  44.             socket = new Socket(HOST, PORT);   
  45.             in = new BufferedReader(new InputStreamReader(socket   
  46.                     .getInputStream()));   
  47.             out = new PrintWriter(new BufferedWriter(   
  48.                     new OutputStreamWriter(socket.getOutputStream())),   
  49.                     true);   
  50.         } catch (Exception ex) {   
  51.             ex.printStackTrace();   
  52.             ShowDialog("登陆异常:" + ex.getMessage());   
  53.         }   
  54.         btn_send.setOnClickListener(new Button.OnClickListener() {   
  55.   
  56.             public void onClick(View v) {   
  57.                 // TODO Auto-generated method stub   
  58.                 String msg = ed_msg.getText().toString();   
  59.                 if (socket.isConnected()) {   
  60.                     if (!socket.isOutputShutdown()) {   
  61.                         out.println(msg);   
  62.                     }   
  63.                 }   
  64.             }   
  65.   
  66.         });   
  67.         new Thread(this).start();   
  68.     }   
  69.   
  70.     public void ShowDialog(String msg) {   
  71.         new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)   
  72.                 .setPositiveButton("OK"new DialogInterface.OnClickListener() {   
  73.   
  74.                     public void onClick(DialogInterface dialog, int which) {   
  75.                         // TODO Auto-generated method stub   
  76.   
  77.                     }   
  78.   
  79.                 }).show();   
  80.     }   
  81.   
  82.     public void run() {   
  83.         try {   
  84.             while (true) {   
  85.                 if(socket.isConnected()){   
  86.                     if(!socket.isInputShutdown()){   
  87.                         if ((content = in.readLine()) != null) {   
  88.                             Log.i("TAG""++ "+content);   
  89.                             content += "/n";   
  90.                             mHandler.sendMessage(mHandler.obtainMessage());   
  91.                         }else{   
  92.                                
  93.                         }   
  94.                     }   
  95.                 }   
  96.                    
  97.             }   
  98.         } catch (Exception ex) {   
  99.             ex.printStackTrace();   
  100.         }   
  101.     }   
  102.   
  103.     public Handler mHandler = new Handler() {   
  104.         public void handleMessage(Message msg) {   
  105.             super.handleMessage(msg);   
  106.             Log.i("TAG""-- "+msg);   
  107.             tv_msg.setText(tv_msg.getText().toString() + content);   
  108.         }   
  109.     };   
  110. }  
package com.Aina.Android;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Test extends Activity implements Runnable {
	/** Called when the activity is first created. */
	private TextView tv_msg = null;
	private EditText ed_msg = null;
	private Button btn_send = null;
	private Button btn_login = null;
	private static final String HOST = "192.168.0.132";
	private static final int PORT = 9999;
	private Socket socket = null;
	private BufferedReader in = null;
	private PrintWriter out = null;
	private String content = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tv_msg = (TextView) this.findViewById(R.id.TextView);
		ed_msg = (EditText) this.findViewById(R.id.EditText01);
		btn_login = (Button) this.findViewById(R.id.Button01);
		btn_send = (Button) this.findViewById(R.id.Button02);
		try {
			socket = new Socket(HOST, PORT);
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
			out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream())),
					true);
		} catch (Exception ex) {
			ex.printStackTrace();
			ShowDialog("登陆异常:" + ex.getMessage());
		}
		btn_send.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String msg = ed_msg.getText().toString();
				if (socket.isConnected()) {
					if (!socket.isOutputShutdown()) {
						out.println(msg);
					}
				}
			}

		});
		new Thread(this).start();
	}

	public void ShowDialog(String msg) {
		new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}

				}).show();
	}

	public void run() {
		try {
			while (true) {
				if(socket.isConnected()){
					if(!socket.isInputShutdown()){
						if ((content = in.readLine()) != null) {
							Log.i("TAG", "++ "+content);
							content += "/n";
							mHandler.sendMessage(mHandler.obtainMessage());
						}else{
							
						}
					}
				}
				
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.i("TAG", "-- "+msg);
			tv_msg.setText(tv_msg.getText().toString() + content);
		}
	};
}


Java代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">   
  5.     <TextView android:id="@+id/TextView" android:singleLine="false"  
  6.         android:layout_width="fill_parent"  
  7.         android:layout_height="wrap_content" />   
  8.     <EditText android:hint="content" android:id="@+id/EditText01"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content">   
  11.     </EditText>   
  12.     <Button android:text="login" android:id="@+id/Button01"  
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content">   
  15.     </Button>   
  16.     <Button android:text="send" android:id="@+id/Button02"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content">   
  19.     </Button>   
  20. </LinearLayout>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值