怎样使用socket来实现简单的点对点通信

 我来答
福喜900
2015-01-11 · TA获得超过6.1万个赞
知道大有可为答主
回答量:1.1万
采纳率:0%
帮助的人:1亿
展开全部
要用android实现点对点通信,可以使用socket完成,使用socket需要知道对方的IP地址以及端口号,这里我省略了服务器端(编写正规的通信软件还是得需要服务器做中转,用服务器得知A的IP地址,然后让A做服务器端,B用A的Ip地址去获取数据),只是展示相关原理,首先看服务器端
1 package polly.liu;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.net.InetAddress;
7 import java.net.NetworkInterface;
8 import java.net.ServerSocket;
9 import java.net.Socket;
10 import java.net.SocketException;
11 import java.util.Enumeration;
12
13 import android.app.Activity;
14 import android.os.Bundle;
15 import android.os.Handler;
16 import android.util.Log;
17 import android.widget.TextView;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.net.ServerSocket;
23 import java.net.Socket;
24 import android.app.Activity;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.os.Message;
28 import android.widget.TextView;
29
30 public class ServerActivity extends Activity {
31 ServerSocket ss = null;
32 String mClientMsg = "";
33 Thread myCommsThread = null;
34 protected static final int MSG_ID = 0x1337;
35 public static final int SERVERPORT = 6000;
36
37 @Override
38 public void onCreate(Bundle savedInstanceState) {
39 super.onCreate(savedInstanceState);
40 setContentView(R.layout.main);
41 TextView tv = (TextView) findViewById(R.id.TextView01);
42 tv.setText("Nothing from client yet");
43 this.myCommsThread = new Thread(new CommsThread());
44 this.myCommsThread.start();
45 }
46
47 @Override
48 protected void onStop() {
49 super.onStop();
50 try {
51 // 确保你退出时要关闭socket连接
52 ss.close();
53 } catch (IOException e) {
54 e.printStackTrace();
55 }
56 }
57
58 Handler myUpdateHandler = new Handler() {
59 public void handleMessage(Message msg) {
60 switch (msg.what) {
61 case MSG_ID:
62 TextView tv = (TextView) findViewById(R.id.TextView01);
63 tv.setText(mClientMsg);
64 break;
65 default:
66 break;
67 }
68 super.handleMessage(msg);
69 }
70 };
71 class CommsThread implements Runnable {
72 public void run() {
73 Socket s = null;
74 try {
75 ss = new ServerSocket(SERVERPORT );
76 } catch (IOException e) {
77 e.printStackTrace();
78 }
79 while (!Thread.currentThread().isInterrupted()) {
80 Message m = new Message();
81 m.what = MSG_ID;
82 try {
83 if (s == null)
84 s = ss.accept();
85 BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
86 String st = null;
87 st = input.readLine();
88 mClientMsg = st;
89 myUpdateHandler.sendMessage(m);
90 } catch (IOException e) {
91 e.printStackTrace();
92 }
93 }
94 }
95 }
96 }

服务器端和平时在PC上的代码差不多,只不过现在把在PC上的代码转到了手机端,注意耗时间的操作要放在子线程上去做,再来看看客户端代码:
1 package polly.liu;
2
3 import java.io.BufferedWriter;
4 import java.io.IOException;
5 import java.io.OutputStreamWriter;
6 import java.io.PrintWriter;
7 import java.net.InetAddress;
8 import java.net.Socket;
9 import java.net.UnknownHostException;
10
11 import android.app.Activity;
12 import android.os.Bundle;
13 import android.util.Log;
14 import android.view.View.OnClickListener;
15 import android.widget.Button;
16 import android.widget.EditText;
17 import android.widget.TextView;
18 import android.view.View;
19
20 public class ClientActivity extends Activity {
21 private Button bt;
22 private TextView tv;
23 private Socket socket;
24 private String serverIpAddress = "192.168.1.104";
25
26 private static final int REDIRECTED_SERVERPORT = 6000;
27 @Override
28 public void onCreate(Bundle savedInstanceState) {
29 super.onCreate(savedInstanceState);
30 setContentView(R.layout.main);
31 bt = (Button) findViewById(R.id.myButton);
32 tv = (TextView) findViewById(R.id.myTextView);
33 try {
34 InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
35 socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
36 } catch (UnknownHostException e1) {
37 e1.printStackTrace();
38 } catch (IOException e1) {
39 e1.printStackTrace();
40 }
41 bt.setOnClickListener(new OnClickListener() {
42 public void onClick(View v) {
43 try {
44 EditText et = (EditText) findViewById(R.id.EditText01);
45 String str = et.getText().toString();
46 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
47 out.println(str);
48 Log.d("Client", "Client sent message");
49 } catch (UnknownHostException e) {
50 tv.setText("Error1");
51 e.printStackTrace();
52 } catch (IOException e) {
53 tv.setText("Error2");
54 e.printStackTrace();
55 } catch (Exception e) {
56 tv.setText("Error3");
57 e.printStackTrace();
58 }
59 }
60 });
61 }
62 }
通过以上的学习,大家可以系统的整理一下具体的操作流程,达内科技是您永远的老师和朋友,如果您还有其他疑问也可以随时关注我们的网页更新内容,达内有很多的信息愿与大家共享。
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式