您的位置:首页 > 理论基础 > 计算机网络

android发送udp,tcp消息

2013-11-14 10:48 197 查看
发送方创建步骤:

1. 创建一个DatagramSocket对象

DatagramSocket socket = new DatagramSocket (4567);

2. 创建一个 InetAddress , 相当于是地址

InetAddress serverAddress = InetAddress.getByName("想要发送到的那个IP地址");

3. 这是随意发送一个数据

String str = "hello";

4. 转为byte类型

byte data[] = str.getBytes();

5. 创建一个DatagramPacket 对象,并指定要讲这个数据包发送到网络当中的哪个地址,以及端口号

DatagramPacket package = new DatagramPacket (data , data.length , serverAddress , 4567);

6. 调用DatagramSocket对象的send方法 发送数据

socket . send(package);

udp的辅助工具类:

这在自己项目中主要用来发送频道号码,如果是1...9自然发送一次即可,如果是多余1位的,就依次发送。

package com.wotlab.home.moneyplantairs.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
* Socket的助手类,用于通过TCP协议发送数据
*
* @author lx
*
*/
public class SocketHelper {
private Socket s = null;
BufferedReader input = null;
PrintWriter output = null;

public SocketHelper() {
}

public void connect(String ip, int port) throws Exception {
s = new Socket();
SocketAddress socAddress = new InetSocketAddress(ip, port);
// SocketAddress socAddress = new InetSocketAddress("192.168.1.105",
// port);
s.connect(socAddress, Constants.SOCKET_TIMEOUT);
s.setSoTimeout(Constants.SOCKET_LINK_TIMEOUT);
}

public void close() throws Exception {
output.close();
input.close();
s.close();
}

public String sendTCP(String str) {
String receive = "";
try {
if (s == null) {
throw new Exception("");
}
output = new PrintWriter(s.getOutputStream());
output.print(str);
output.flush();
input = new BufferedReader(
new InputStreamReader(s.getInputStream()));
receive = input.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return receive;
}
}


发送tcp消息
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: