学习笔记_TCP编程,服务端
public void startTcpService(String ip) {
try { InetAddress ipAddress = InetAddress.getByName(ip); tcpServer = new ServerSocket(TCP_SERVER_PORT, 0, ipAddress); tcpServer.setSoTimeout(1000); SocketHandler handler = new SocketHandler(); new Thread(handler).start(); } catch (Exception e) { logger.info("Start tcp service failed. ip = " + ip + ",port=" + TCP_SERVER_PORT, e); } logger.info("Start tcp service on port, ip = " + ip + ",port=" + TCP_SERVER_PORT); } class SocketHandler implements Runnable { @Override public void run() { while (true) { Socket sock = null; try { sock = tcpServer.accept(); sock.setSoTimeout(490); MyTcpSocket mySockThread = new MyTcpSocket(sock); Thread thread = new Thread(pmSockThread); thread.start(); } catch (SocketTimeoutException e) { // do nothing } catch (Exception e1) { logger.info("Init sockt failed. ip=" + ip , e1); } } } }
public class MyTcpSocket implements Runnable { private static DebugLog logger ; //Socket连接 private Socket sock = null; //接收数据缓冲区 private byte[] dataBuffer = new byte[10240]; //接收数据缓冲区长度 private int dataLen = 0; public MyTcpSocket(Socket sock) { logger.info("New Tcp socket inited."); this.sock = sock; } @Override public void run() { try { int bufLen = 1024; InputStream inStream = sock.getInputStream(); OutputStream outStream = sock.getOutputStream(); buildlinkConnect(outStream); byte recvBuf[] = new byte[bufLen]; int len = 0; while (true) { try { len = inStream.read(recvBuf, 0, bufLen); printlnFromBytes("recv", recvBuf, len);
} catch (SocketTimeoutException e1) { len = 0; } if (len > 0 && recvBuf != null) { outStream.write("response"); } } } catch (Exception e) { } finally { closeSocket(); } }