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

简单介绍

本篇介绍Android网络之Socket通信的UDP方式的使用

实例

此实例用电脑作服务器,手机作客户端实现。
服务端源码

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
package com.carlos.udp;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Server {

public static void main(String[] args) {

int port=3168;
byte[] message=new byte[1024];
//实例化一个DatagramPacket类
DatagramSocket socket=null;
try {
socket=new DatagramSocket(port);
System.out.println("服务端开启"+port+"端口");
//新建一个DatagramSocket类
DatagramPacket packet=new DatagramPacket(message, message.length);
while(true){
socket.receive(packet);

DataInputStream dis=new DataInputStream(new ByteArrayInputStream
(packet.getData(),packet.getOffset(),packet.getLength()));
String result=dis.readUTF();

System.out.println("客户端ip为:"+packet.getAddress()+" 端口为:"
+packet.getPort()+" 发送的消息为:"+result);

}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//如果socket对象不为空,则关闭socket对象
if (socket!=null) {
socket.close();
}
}
}
}

客户端源码

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
110
111
112
113
114
115
package com.carlos.udpclient;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
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();
}
});

}

void connnect() {
String IP = ipAddress.getText().toString();
int TCP_SERVER_PORT = Integer.valueOf(port.getText().toString());
result = message.getText().toString();
DatagramSocket socket;
try {
socket = new DatagramSocket();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(result);
dos.close();

byte[] data = baos.toByteArray();

InetAddress address = InetAddress.getByName(IP);
DatagramPacket packet = new DatagramPacket(data, data.length,
address, TCP_SERVER_PORT);
socket.send(packet);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

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) {
connnect();
return result;
}

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

}

@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;
}
}
}

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:maxLength="100"
android:background="@android:drawable/edit_text" />
</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. 1. 简单介绍
  2. 2. 实例