**
这里主要介绍客户端实现,主要分四步:
**
1.创建socket对象,并指定服务器的地址和端口
2.建立链接后,通过输入输出流写入请求信息
3.通过输入输出流获取服务端返回的信息
4.关闭相关资源
下面是相关代码:
public class TcpClientService {
private static final Log LOG = LogFactory.getLog(TcpClientService.class);
//从配置文件获取服务端地址和端口
private static final String TCP_ADDRESS = PropertiesUtil.getProperty("tcp.address");
private static final String TCP_PORT = PropertiesUtil.getProperty("tcp.port");
public static String sendRequest(String request) throws IOException {
String response = "";
StringBuilder sb = new StringBuilder();
Socket socket = null;
PrintWriter pWriter = null;
OutputStream outputStream = null;
OutputStreamWriter oWriter = null;
InputStream inputStream = null;
BufferedReader bReader = null;
try {
LOG.info("=====+++++===发送的IP和端口===+++++++===");
LOG.info("URL is " + TCP_ADDRESS + ":" + TCP_PORT);
//创建socket对象并指定服务端地址和端口
socket = new Socket(TCP_ADDRESS, Integer.parseInt(TCP_PORT));
//打开输入输出流
outputStream = socket.getOutputStream();
pWriter = new PrintWriter(outputStream);
oWriter = new OutputStreamWriter(outputStream, "UTF-8");
String sendString = request;
int num = sendString.getBytes("UTF-8").length;
String tString = null;
tString = String.format("%0" + 8 + "d", num);
oWriter.write(tString + sendString);
oWriter.flush();
LOG.info(tString + sendString);
//关闭输出流
socket.shutdownOutput();
// 返回报文
inputStream = socket.getInputStream();
//在缓冲区内包装字符流以提高效率
bReader = new BufferedReader(new InputStreamReader(inputStream,
"UTF-8"));
String tmp = "";
while ((tmp = bReader.readLine()) != null) {
sb.append(tmp);
}
response = sb.toString();
LOG.info("=====++++返回的报文如下:++++=====" + response);
socket.shutdownInput();
} catch (UnknownHostException e) {
// TODO: handle exception
LOG.error("UnknownHostException", e);
} catch (IOException e) {
// TODO: handle exception
LOG.error("IOEXception", e);
}
//关闭相关资源
finally {
if (bReader != null) {
bReader.close();
}
if (inputStream != null) {
inputStream.close();/**/
}
if (pWriter != null) {
pWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (socket != null) {
socket.close();
}
}
// 截取返回报文中的字符数统计
response = response.substring(8);
return response;
}
}