android 模拟器和pc服务器端用socket通讯

开始不能进行通讯,错误原因主要在IP和端口,IP要用本机IP,端口用emulator的名称,如:5554; 服务器端要建一个java工程(run application)

同时不要忘记:<uses-permission android:name="android.permission.INTERNET"/>

模拟器 客户端代码如下:


package com.socket.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

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

public class SocketActivity extends Activity {
    EditText editText = null;
    Button sendButton = null;
    TextView display = null;
    Socket client = null;
    MyHandler myHandler;
    DataOutputStream dout;
    DataInputStream din;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        editText = (EditText)findViewById(R.id.message);
        sendButton = (Button)findViewById(R.id.send);
        display = (TextView)findViewById(R.id.display);
        sendButton.setOnClickListener(listener);
        try {
			client = new Socket("172.168.11.167",5554);
			dout = new DataOutputStream(client.getOutputStream());
			din = new DataInputStream(client.getInputStream());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        myHandler = new MyHandler();
        MyThread m = new MyThread();
        m.start();
    }
    //http://fengshen1.me3g.cn/Inter_Conn_Charge/get_charge_method_path.aspx?scrsize=240X320&sc=0&pl=0&IMSI=9460008691342477&vs=0&IMEI=862880000000000&pv=mcare&cid=0&lac=0&smsc=0
    class MyHandler extends Handler{
    	public MyHandler(){	
    	}
    	@Override
    	public void handleMessage(Message msg){
    		Log.d("MyHandler","handleMessage.......");
    		super.handleMessage(msg);
    		//此处可以更新UI
    		
    		if(client != null && client.isConnected()){
    			Log.i("handler..","*------*");
    			
    			try {
					dout.writeUTF("connect...");
					String message  = din.readUTF();
					if(!message.equals("")){
						display.setText(display.getText().toString() + "\n" + "服务器发来的消息--:" + message );
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    		}
    	}
    	
    }

    class MyThread extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message msg = new Message();
				SocketActivity.this.myHandler.sendMessage(msg);
			}
		}
    }
    OnClickListener listener = new OnClickListener(){
    	public void onClick(View v){
    		String sendText = editText.getText().toString();
    		try{
    			dout.writeUTF(sendText);
    		}catch(UnknownHostException e){
    			e.printStackTrace();
    		}catch(IOException e){
    			e.printStackTrace();
    		}
    	}
    };
 }


main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
	android:id="@+id/message"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	/>
    
    <Button
	android:id="@+id/send"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="send"
	/>
    
        <TextView
         android:id="@+id/display"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>


服务器端代码:

package test.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

	static ServerSocket aServerSocket = null;  //server Socket 
	DataInputStream aDataInput = null; //Server input Stream that to receive msg from client
	
	DataOutputStream aDataOutput = null;//Server output Stream that to
	
	static ArrayList list = new ArrayList();
	
	public static void main(String[] args){
		try {
			aServerSocket = new ServerSocket(5554);//listen 8888 port
			System.out.println("already listen 5554 port");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		int num = 0;
		while(num < 10){
			Socket aSessionSocket = null;
			try {
				aSessionSocket = aServerSocket.accept();
				MyThread thread = new Server().new MyThread(aSessionSocket);
				thread.start();
				num = list.size();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}

	class MyThread extends Thread{
		Socket aSessionSocket = null;
		public MyThread(Socket socket){
			aSessionSocket = socket;
		}
		
		public void run(){
			try {
				aDataInput = new DataInputStream(aSessionSocket.getInputStream());
				aDataOutput = new DataOutputStream(aSessionSocket.getOutputStream());
				list.add(aDataOutput);
				
				while(true){
					String msg = aDataInput.readUTF(); //read msg
					if(!msg.equals("connect...")){
						System.out.println("ip:" + aSessionSocket.getInetAddress()); //ip
						System.out.println("receive msg:" + msg);
						for(int i = 0; i < list.size(); i++){
							DataOutputStream output = (DataOutputStream)list.get(i);
							output.writeUTF(msg + "----" + list.size());
						}
						if(msg.equals("end")){
							break;
						}
					}
					aDataOutput.writeUTF("");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					aDataInput.close();
					if(aDataOutput != null){
						aDataOutput.close();
					list.remove(aDataOutput);
					aSessionSocket.close();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}
}


你可能感兴趣的:(android,exception,socket,服务器,layout,null)