Android socket programming example

  sonic0002        2013-05-11 22:17:16       56,528        3    

Socket is a kind of interface for different sides t communicate, it usually identified by an IP and a port. There are many server side software on a server and they would provide different service. Each server many create some sockets and bind them to some ports so that clients can listen to.

Software on the Internet will exchange data though a bidirectional connection established. Each end of the connection has a socket created. In Java, Socket and ServerSocket are in java.net package, ServerSocket is used for server side and Socket is used when establishing connection. Once a successful connection is established, each end of the connection will create a Socket instance.

Here we introduce a very simple client and server connection example in Android.

Server side will bind to port 9999, if there is a request from client, it will respond to the request and then continues to listen to requests.

Server side

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

public class Main {
	private static final int PORT = 9999;
	public static void main(String[] args) {

		try {
			// Create ServerSocket instance and bind it to port 9999
			ServerSocket server = new ServerSocket(PORT);
			while (true) {
				Socket socket = server.accept();
				// Get output buffer
				BufferedWriter writer = new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream()));
				// Write output
				writer.write("这是一段来自服务器的问候:Hello沃德!");
				writer.flush();
				writer.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

Client side:

com.example.socketdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
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.TextView;

@SuppressLint("HandlerLeak")
public class SocketDemo extends Activity {
	/** Called when the activity is first created. */
	private Button btn_receive;
	private TextView txt;
	private String line;
	
	private static final String HOST = "192.168.1.101";  
	private static final int PORT = 9999;  


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initControl();
	}

	private void initControl() {
		btn_receive = (Button) findViewById(R.id.btn_receive);
		txt = (TextView) findViewById(R.id.txt);
		btn_receive.setOnClickListener(new ReceiverListener());
	}

	
	@SuppressLint("HandlerLeak")
	class ReceiverListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new Thread() {
				@Override
				public void run() {
					try {
						// Create Socket instance
						Socket socket = new Socket(HOST, PORT);
						// Get input buffer
						BufferedReader br = new BufferedReader(
								new InputStreamReader(socket.getInputStream()));
						line = br.readLine();
						br.close();
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.sendEmptyMessage(0);
				}
			}.start();
		}

	}

	// Define Handler object
	private Handler handler = new Handler() {
		@Override
		// When there is message, execute this method
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// Update UI
			txt.setText(line);
			Log.i("PDA", "----->" + line);
		}
	};

}

The effect:

Don't forget to add permission in the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET">

Start server first when doing testings.

Source : http://blog.csdn.net/eyu8874521/article/details/8847173

ANDROID  SOCKET  JAVA 

       

  RELATED


  3 COMMENTS


niko [Reply]@ 2013-08-06 23:16:25

oh,shit,chinese

Anonymous [Reply]@ 2017-03-04 01:46:07

lol

Anonymous [Reply]@ 2017-08-13 12:44:13

This is not helpful when trying to make the socket available across multiple activities. You should have shown an example using the Services



  RANDOM FUN

TCP vs UDP