之前写过一些关于TCP和UDP数据传输的代码,比如使用TCP传输音视频数据包,P2P打洞中使用UDP等。写好之后就直接丢下了,没有总结下都。最近准备找工作,再拿来温习下。
暂时把自己的定位很明确,就是android应用层的开发,所以关于TCP/UDP的实现细节,暂时也不想去深究。但是心里清楚这个必须去看的,有时间推荐大家看看《TCP/IP详解》,或者网上有很多大牛的总结。
1
|
newSocket(ip, prot);
|
1
2
|
InputStream is = mSocket.getInputStream();
OutputStream out = mSocket.getOutputStream();
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@Override
publicvoidexecute() {
try{
intcount = is.read(receiveBuffer);
if(count == -1) {
notifyError();
}
byte[] data = getPacket(receiveBuffer, count, is);
mReceiverQueue.put(data);
}catch(InterruptedException e) {
e.printStackTrace();
notifyError();
}catch(IOException e) {
e.printStackTrace();
notifyError();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Override
publicvoidexecute() {
try{
byte[] data = mSenderQueue.take();
out.write(data);
}catch(InterruptedException e) {
e.printStackTrace();
notifyError();
}catch(IOException e) {
e.printStackTrace();
notifyError();
}
}
|
1
2
3
4
5
6
7
8
9
|
try{
ServerSocket serverSocket =newServerSocket(9559);
while(true) {
Socket socket = serverSocket.accept();
// new ServiceSocketThread(socket).start();
}
}catch(Exception e) {
e.printStackTrace();
}
|
这个东西用的很少,就是当初测试P2P的时候用过。能想到的问题就是数据大小的问题,比如发送数据我们的数据定义为多大合适。但是最后没有实际的项目验证,在此也不好回答。先贴一段代码出来:
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
|
publicclassUDPServerextendsBaseThread {
/** 发送队列大小 */
publicstaticfinalintSENDQUEUESIZE =10;
/** 接收队列大小 */
publicstaticfinalintRECEIVEQUEUESIZE =10;
/** TCP接收缓存大小 */
publicstaticfinalintRECEIVERBUFFERSIZE =1024;
/** UDP接收缓存大小 */
publicstaticfinalintRECEIVERPACKETSIZE =1024*64;
privateintcount =0;
privateDatagramPacket receivePacket;
privateDatagramSocket mSocket;
@Override
publicbooleanprepare() {
receivePacket =newDatagramPacket(newbyte[RECEIVERPACKETSIZE], RECEIVERPACKETSIZE);
try{
mSocket =newDatagramSocket(9559);
}catch(SocketException e) {
System.out.println(String.format("udp connect init error: %s", e.getMessage()));
returnfalse;
}
returntrue;
}
@Override
publicvoidexecute() {
try{
mSocket.receive(receivePacket);
byte[] data = receivePacket.getData();
intlength = receivePacket.getLength();
intoffset = receivePacket.getOffset();
System.out.print(++count
+ String.format("length:%d|%d, offset:%d, data: %s \n", length, data.length, offset,newString(data,"gbk")));
System.out.println(data[1024]);
}catch(SocketException e) {
System.out.println(String.format("udp connect init error: %s", e.getMessage()));
}catch(IOException e) {
System.out.println(String.format("udp connect init error: %s", e.getMessage()));
}
}
}
|