Android 开发TCP、UdP客户端

在进行Android开发的过程中,免不了,要开发TCP/UDP通讯的程序,下面这两段代码,分别介绍了TCP/UCP通过的一个实例:

代码一:

 

private void tcpdata() {

try {

Socket s = new Socket("192.168.0.25", 65500);

// outgoing stream redirect to socket

OutputStream out = s.getOutputStream();

// 注意第二个参数据为true将会自动flush,否则需要需要手动操作out.flush()

PrintWriter output = new PrintWriter(out, true);

 

output.println("Hello IdeasAndroid! 伪IP为:"

+ SIMCardToIP("13512345006"));

 

InputStream inputStream = s.getInputStream();

 

DataInputStream input = new DataInputStream(inputStream);

 

byte[] b = new byte[10000];

 

int length = input.read(b);

 

inputReader = new InputStreamReader(inputStream);

 

String Msg = new String(b, 0, length, "gb2312");

 

Toast.makeText(TcpTest.this, Msg, 1000).show();

 

Log.d("Tcp Demo", "message From Server:" + Msg);

s.close();

 

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

下面的代码是UDP通讯的过程:
public String send(String msg) {
StringBuilder sb = new StringBuilder();
InetAddress local = null;
try {
local = InetAddress.getByName("192.168.0.25"); // 本机测试
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
dSocket = new DatagramSocket(); // 注意此处要先在配置文件里设置权限,否则会抛权限不足的异常
} catch (SocketException e) {
e.printStackTrace();
}
int msg_len = msg == null ? 0 : msg.length();
DatagramPacket dPacket = new DatagramPacket(msg.getBytes(), msg_len,
local, SERVER_PORT);
try {
dSocket.send(dPacket);
} catch (IOException e) {
e.printStackTrace();
}
try {
dSocket.receive(dPacket);
sb.append(new String(dPacket.getData()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dSocket.close();
return sb.toString();
}

 

 

 

 

你可能感兴趣的:(Android 开发)