工作需要向TCP服务器发送命令,就研究了一下,结合网上的资料,成果代码片段如下:
- 客户端发送信息方法
-
/** * TCP:发送消息 * @throws Exception */ public void clientTest() throws Exception { Socket sk = null; OutputStream os = null; try { String send = getPara("send"); sk = TestTcpClient.getSocket(); if (sk != null) { try { sk.sendUrgentData(0XFF); } catch (Exception e) { if (times < 5) { times = times + 1; System.out.println("第" + times + "次重连..."); TestTcpClient.reConnection(); clientTest(); }else { times = 0; renderJson("重连失败!"); return; } } } if (StrKit.notBlank(send)) { //给服务端发送响应信息 os = sk.getOutputStream(); os.write(send.getBytes()); } getTcpInfo(); //等待响应 } catch (ConnectException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { throw e; } }
客户端接收信息方法
-
/** * 接收TCP消息 */ public void getTcpInfo() { InputStream is = TestTcpClient.getInputStream(); byte b[] = new byte[1024]; try { TestTcpClient.getSocket().setSoTimeout(10000); is.read(b); } catch (SocketTimeoutException e) { if (times < 5) { times += 1; System.out.println("第" + times + "次重连..."); TestTcpClient.reConnection(); getTcpInfo(); }else { times = 0; renderJson("重连失败!"); return; } } catch (IOException e) { e.printStackTrace(); } System.out.println(new String(b)); }
- 获取链接TCP/IP服务器的实例
-
package com.coobar.desktop.config;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket; import java.net.UnknownHostException;//后启动客户端程序 public class TestTcpClient { private static Socket sk = null; static { //建立Socket实例 try { //对服务端发起连接请求 sk = new Socket("127.0.0.1", 60); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { throw e; } System.out.println("初始化链接........"); } /** * 获取socket实例 * @return */ public static Socket getSocket() { return sk; } /** * 关闭socket实例 */ public static void close() { try { sk.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取socket实例的输入流(接收信息) * @return */ public static InputStream getInputStream() { InputStream stream = null; try { stream = sk.getInputStream(); } catch (IOException e) { e.printStackTrace(); } return stream; } /** * 获取socket的输出流(发送信息) * @return */ public static OutputStream getOutputStream() { OutputStream stream = null; try { stream = sk.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } return stream; } /** * 重新连接socket */ public static void reConnection() { try { sk = new Socket("127.0.0.1", 60); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}