1. 程式人生 > >Android客戶端與PC進行Socket通訊

Android客戶端與PC進行Socket通訊

伺服器端程式碼:

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


public class SimServer {

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

		try {
			ServerSocket serverSocket=new ServerSocket(30000);
			while(true){
				Socket socket=serverSocket.accept();
				OutputStream outputStream=socket.getOutputStream();
				outputStream.write("Heello This Server".getBytes("UTF-8"));
				outputStream.close();
				socket.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}


android客戶端:

package com.SimpleClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SimpleClientActivity extends Activity {
    /** Called when the activity is first created. */
	private Button button;
	private TextView textView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button=(Button)this.findViewById(R.id.button1);
        textView=(TextView)this.findViewById(R.id.textView);
        button.setOnClickListener(new BtnListener());
    }
    private final class BtnListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			try {
				Socket socket=new Socket("59.69.105.217", 30000);
				BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				String line=br.readLine();
				textView.setText(line);
				
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
    	
    }
}


結果: