TCP通信工具
package com.dobot.androidtools.Tools;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.URLDecoder;
public class TCPTool {
public static TCPTool tcpTool;
/**
* 获取CrashHandler实例 ,单例模式
*/
public static TCPTool getInstance() {
if (tcpTool == null)
tcpTool = new TCPTool();
return tcpTool;
}
/**
* 以下是TCP协议的通讯请求
*
* @param HOST
* @param PORT
* @param CONTENT
*/
public void TCPSend(String HOST, int PORT, String CONTENT) {
Socket socket = null;
try {
socket = new Socket(HOST, PORT);
try {
//对服务端发起连接请求
//给服务端发送响应信息
String strUTF8 = URLDecoder.decode(CONTENT, "UTF-8");
String result = new String(strUTF8.getBytes("UTF-8"), "UTF-8");
// 读取服务器端传过来信息的DataInputStream
DataInputStream in = new DataInputStream(socket.getInputStream());
// 向服务器端发送信息的DataOutputStream
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String sendString = result;
//将客户端的信息传递给服务器
out.writeUTF(sendString);
L.c("ip:" + HOST + "--端口:" + PORT + "--发送的字符串:" + result);
// 读取来自服务器的信息
String accpet = in.readUTF();
L.c("收到的数据是:" + accpet);
} finally {
socket.close();//关闭Socket监听
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
网友评论