search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Android]Sample Socket Server & Client – 佛祖球球

一開始要先在Manifest新增權限

Manifest:




    
    
    
	
	
	
	

    
        
            
                

                
            
        
    


Server:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import android.net.wifi.WifiInfo;

public class Socket_test extends Activity {
    
	TextView test;
	TextView test2;
	
	private Handler handler = new Handler();
    private ServerSocket serverSocket;
    private String line ;
    
    
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        test = (TextView) findViewById( R.id.test );
        test2 = (TextView) findViewById( R.id.test2 );
        
        //建立Thread
        Thread fst = new Thread(socket_server);
		//啟動Thread
        fst.start();
        
    }
    
    //取得IP
  	private String getMyIp(){
          //新增一個WifiManager物件並取得WIFI_SERVICE
  		WifiManager wifi_service = (WifiManager)getSystemService(WIFI_SERVICE);
  		//取得wifi資訊
  		WifiInfo wifiInfo = wifi_service.getConnectionInfo();
  		//取得IP,但這會是一個詭異的數字,還要再自己換算才行
  		int ipAddress = wifiInfo.getIpAddress();
  		//利用位移運算和AND運算計算IP
  		String ip = String.format("%d.%d.%d.%d",(ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
  		return ip;
  	}
  	
  	
  	private Runnable socket_server = new Runnable(){
  		public void run(){
  			handler.post(new Runnable() {
				public void run() {
					test.setText("Listening...." + getMyIp());
				}
			});
  			
  			try{
  				//建立serverSocket
				serverSocket = new ServerSocket(1234);
				
				//等待連線
				while (true) {
					//接收連線
					Socket client = serverSocket.accept();
					
					handler.post(new Runnable() {
						public void run() {
							test.setText("Connected.");
						}
					});
					try {
						//接收資料
						DataInputStream in = new DataInputStream(client.getInputStream());
						line = in.readUTF();
						while (line != null) {
							handler.post(new Runnable() {
								public void run() {
									test2.setText(line);
								}
							});
						}
						break;
					} catch (Exception e) {
						handler.post(new Runnable() {
							public void run() {
								test.setText("傳送失敗");
							}
						});
					}
				}
  			}catch(IOException e){
  				handler.post(new Runnable() {
  					public void run() {
						test.setText("建立socket失敗");
					}
				});
  			}
  		}
    };
}

Client:

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Socket_test extends Activity {
	
	TextView test;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        test = (TextView) findViewById( R.id.test );
        
        InetAddress serverAddr = null;
        SocketAddress sc_add = null;
        Socket socket = null;
        //要傳送的字串
        String message = "Hello Socket";
        
		try {
			//設定Server IP位置
			serverAddr = InetAddress.getByName("120.119.112.168");
			//設定port:1234
			sc_add= new InetSocketAddress(serverAddr,1234);
			
			socket = new Socket();
			//與Server連線,timeout時間2秒
			socket.connect(sc_add,2000);
			
			//傳送資料
			DataOutputStream out = new DataOutputStream(socket.getOutputStream());
			out.writeUTF(message);
			
			//關閉socket
			socket.close();
			
		} catch (UnknownHostException e) {
			test.setText("InetAddress物件建立失敗");
		} catch (SocketException e) {
			test.setText("socket建立失敗");
		} catch(IOException e) {
			test.setText("傳送失敗");
		} 
    }
}
Categories: Android

3 Comments

Sky · 3 月 9, 2012 at 9:32 下午

哈囉
偶然看到你的文章
想問你 檔案之間傳輸 client端 我要往哪些方面下手
困擾很久了~

My Homepage · 8 月 20, 2012 at 3:59 上午

… [Trackback]…

[…] Read More here: blog.johnsonlu.org/?p=989 […]…

URL · 4 月 10, 2018 at 12:53 下午

… [Trackback]

[…] Read More here: blog.johnsonlu.org/androidsocket/ […]

Comments are closed.



熱門推薦

本文由 blogjohnsonluorg 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦