Socket在Android中的应用

作者:郝浩


         Android 提供的常用的网络编程包括针对TCP/IP协议的Socket通信。Socket是一种跨平台的编程方式,可以在异构语言之间进行通信。

Socket程序的开发原理,是要实现服务器端和客户端。

服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。
  客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。

下面是一个实现socket的例子:

服务器端代码:


package com.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* com Server
*/
public class Main {
	private int ServerPort = 9999;
	private ServerSocket serversocket = null;
	private OutputStream outputStream = null;
	private InputStream inputStream = null;
	private PrintWriter printWinter = null;
	private Socket socket = null;
	private BufferedReader reader = null;
	
	public Main(){
		try{
			serversocket = new ServerSocket(ServerPort);
			System.out.println("服务启动。。。");
			socket = serversocket.accept();
			System.out.println("客户已连接");
			
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		try{
			outputStream= socket.getOutputStream();
			inputStream = socket.getInputStream();
			printWinter = new PrintWriter(outputStream,true);
			reader = new BufferedReader(new InputStreamReader(inputStream));
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			while (true){
				String message = reader.readLine();
				System.out.println("client:"+message);
				if(message.equals("bye")||message.equals("Bye")){
					break;
				}
				message = in.readLine();
				printWinter.println(message);
				
			}
			outputStream.close();
			inputStream.close();
			socket.close();
			serversocket.close();
			System.out.print("Client is disconnected");
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			
		}
	
	}
	public static void main(String[] args){
		new Main();
	}
}

客服端代码:

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


XML文件布局:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/TextView" android:singleLine="false"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" />
<EditText android:hint="content" android:id="@+id/EditText01"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
</EditText>
<Button android:text="login" android:id="@+id/Button01"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
</Button>
<Button android:text="send" android:id="@+id/Button02"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
</Button>
</LinearLayout>

先启动服务器端,再运行客户端程序。

注意:(一)即使服务器端和客户端在一台机器上运行,也不能使用ip地址:127.0.0.1,否则,程序会出现拒绝连接的错误。

(二)客户端和服务器端最好不要建在一个工程下,最好是分别建立工程,然后启动服务器端和客户端,否则会报Error: ShouldNotReachHere()错误。这是因为Android程序不是已main方法为程序的入口。

运行效果:






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值