Androidにおけるprotobufベースのsocket通信の例

6008 ワード

Protobufの取得、使い方については、この記事を参照してください.http://www.cnblogs.com/reborter/archive/2012/06/04/2535213.html
次に、私のインスタンスを直接貼り付けます.プロジェクトは後でダウンロードできます.
一、protoプロトコル:

package pbmsg;

option java_outer_classname="UserProto";//  .Java     

message User{
	//        ,        
    required int32 id=1; 
    required int64 id=2; // long  ;
    required string userName=3;
    required string password=4;
    optional string age=5; //required  ,optional  
}

message PbGetAlluser
{ 
	repeated User userList 	= 10;//    
        int32 listSize = 11;
};

コンパイルコマンド:

protoc.exe --java_out=./ User.proto

二、サービス端:
Android中基于protobuf的socket通信的实例
キー・コードJava

package com.jerome.test;

public class Main {

	public static void main(String[] args) {
		new Thread(new DealThread()).start();
	}
}

DealThread.Java

package com.jerome.test;

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

import pbmsg.UserProto.User;

public class DealThread implements Runnable {

	ServerSocket sSocket = null;

	@Override
	public void run() {
		try {
			sSocket = new ServerSocket(12345);
			while (true) {
				Socket socket = sSocket.accept();
				InputStream inputstream = socket.getInputStream();

				byte len[] = new byte[1024];
				int count = inputstream.read(len);
				byte[] temp = new byte[count];
				for (int i = 0; i < count; i++) {
					temp[i] = len[i];
				}

				User user = User.parseFrom(temp);
				System.out.println(user.getID());
				System.out.println(user.getUserName());
				System.out.println(user.getPassword());
				

				User uproto = User.newBuilder().setID(88888888)
						.setPassword("654321").setUserName("zwq").build();
				uproto.writeTo(socket.getOutputStream());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

三、クライアント
Android中基于protobuf的socket通信的实例

package com.jerome.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import pbmsg.UserProto.User;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	Button button = null;
	TextView text = null;
	Socket socket = null;

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

		button = (Button) findViewById(R.id.button);
		text = (TextView) findViewById(R.id.text);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//             ;
				
				//    
				new Thread() {
					public void run() {
						sendText();
					}
				}.start();

				//    
				new Thread() {
					public void run() {
						getText();
					}
				}.start();
			}

		});
	}

	private void sendText() {
		try {
			socket = new Socket("192.168.7.119", 12345);
			User uproto = User.newBuilder().setID(147258369)
					.setPassword("123456").setUserName("jerome").build();
			uproto.writeTo(socket.getOutputStream());

			//         ,            
//			InputStream inputstream = socket.getInputStream();
//			byte len[] = new byte[1024];
//			int count = inputstream.read(len);
//			byte[] temp = new byte[count];
//			for (int i = 0; i < count; i++) {
//				temp[i] = len[i];
//			}

//			User user = User.parseFrom(temp);
//			Log.i("zwq", "Id:" + user.getID() + "____" + user.getUserName() + "____" + user.getPassword());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	private void getText() {
		while (true) {
			try {
				if (null != socket) {
					InputStream inputStream = socket.getInputStream();
					if (null != inputStream) {
						byte len[] = new byte[1024];
						int count = inputStream.read(len);
						byte[] temp = new byte[count];
						for (int i = 0; i < count; i++) {
							temp[i] = len[i];
						}

						User user = User.parseFrom(temp);
						Log.i("zwq","Id:" + user.getID() + "____"+ user.getUserName() + "____"+ user.getPassword());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}