文章目录
  1. 1. 简单介绍
  2. 2. 实例

简单介绍

在Android中除了Http通信比较常用还有Socket通信也用得比较多,Socket通信有面向连接的TCP方式,和无连接的UDP方式,本篇先介绍TCP的使用。

实例

本例用Java在电脑上做服务端开启Socket端口供客户端连接
服务端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.carlos.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

public static void main(String[] args) {

int port=3123;
boolean endFlag=false;
try {
//开启服务器端口
ServerSocket serverSocket=new ServerSocket(port);
System.out.println("服务器端口号:"+port+"已开启");
while(!endFlag){
//等待客户端连接
Socket socket=serverSocket.accept();
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//第二个参数为true将会自动flush,否则需要手动操作writer.flush()
PrintWriter writer=new PrintWriter(socket.getOutputStream(),true);
String message=reader.readLine();
System.out.println("收到"+socket.getInetAddress()+"请求发送给服务器的消息:"+message);
writer.println("你发送给服务器的消息:"+message+" 已经发送成功");

if ("shutdown".equals(message)) {
endFlag=true;
}
socket.close();
}
serverSocket.close();

} catch (IOException e) {
e.printStackTrace();
}

}
}

XML布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="服务器ip地址" />

<EditText
android:id="@+id/ipAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:drawable/edit_text" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="服务器开启的端口号" />

<EditText
android:id="@+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/edit_text" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="想要发送的信息" />

<EditText
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/edit_text"
android:maxLength="100" />
</LinearLayout>

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送信息" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/receive"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="接收到服务器返回的信息:\n" />
</ScrollView>

</LinearLayout>

客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.carlos.tcpclient;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
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 {

private TextView ipAddress;
private TextView port;
private TextView message;
private Button send;
private TextView receive;
private String result;

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

ipAddress = getViewById(R.id.ipAddress);
port = getViewById(R.id.port);
message = getViewById(R.id.message);
send = getViewById(R.id.send);
receive = getViewById(R.id.receive);

send.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Task task = new Task();
task.execute();
}
});
}

private void connect() {

String IP = ipAddress.getText().toString();
int TCP_SERVER_PORT = Integer.valueOf(port.getText().toString());
Socket socket;
try {
socket = new Socket(IP, TCP_SERVER_PORT);

OutputStream stream = socket.getOutputStream();
// 二个参数据为true将会自动flush,否则需要需要手动操作stream.flush()
PrintWriter writer = new PrintWriter(stream, true);
result = message.getText().toString();
writer.println(result);

BufferedReader reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
result = reader.readLine();
socket.close();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

@SuppressWarnings("unchecked")
<T extends View> T getViewById(int id) {
try {
return (T) findViewById(id);
} catch (ClassCastException e) {
Log.e("MainActivity", "Could not cast View to create class.", e);
throw e;
}
}

class Task extends AsyncTask<Void, Void, String> {

ProgressDialog dialog;

@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "", "发送数据中,请稍后...",
true, true);
}

@Override
protected String doInBackground(Void... arg0) {
connect();
return result;
}

@Override
protected void onPostExecute(String result) {
dialog.dismiss();
receive.append(result + "\n");
}
}
}

服务端开启一个端口,把客户端做成的apk安装到手机上后在联网的情况下输入服务端ip地址、服务端开启的端口号、以及客户端想要传递给服务端的信息然后点击发送按钮即可向服务器发送信息。服务器收到信息后在控制台打印出收到的客户端发送的信息,并且客户端显示服务端返回的信息。
以下是服务端控制台输出的信息

以下是客户端信息的信息

文章目录
  1. 1. 简单介绍
  2. 2. 实例