java socket客户端代码_java socket简单客户端

1 packagecom.olcom.socket;2

3 importjava.io.DataInputStream;4 importjava.io.DataOutputStream;5 importjava.io.IOException;6 importjava.net.InetSocketAddress;7 importjava.net.Socket;8 importjava.net.SocketAddress;9 importjava.nio.charset.StandardCharsets;10 importjava.util.Date;11 importlombok.extern.slf4j.Slf4j;12

13 /**

14 * .15 *16 * @ClassName: SocketClient17 * @Auther: olcom18 * @Date: 2019/8/29 11:29:2819 * @Version: iom-cloud-platformV1.020 * @Description: socket 客户端,简单封装.21 **/

22 @Slf4j23 public classSocketClient {24

25 privateString ip;26 private intport;27 privateSocket socket;28 privateDataOutputStream dataOutputStream;29 privateDataInputStream dataInputStream;30 private Date useDate; //连接使用时间,用于判断session失效

31

32 public SocketClient(String ip, intport) {33 this.ip =ip;34 this.port =port;35 useDate = newDate();36 }37

38 public void connect() throwsException {39 log.debug("Entry Method:connect()");40 try{41 close(); //1.主动释放连接//2.某些服务器对指定ip有链路数限制

42

43 socket = newSocket();44 //socket.setKeepAlive(true);

45 SocketAddress socketAddress = newInetSocketAddress(ip, port);46 socket.connect(socketAddress, 1000); //某些服务器ping延迟高时要增加,否则会报错connect timeout

47

48 dataOutputStream = newDataOutputStream(socket.getOutputStream());49 dataInputStream = newDataInputStream(socket.getInputStream());50

51 updateUseDate();52 } catch(Exception e) {53 socket = null;54 log.error("socket connect error ip:" + ip + ",port:" + port + ",Exception:" +e.getMessage());55

56 throw newException(57 "socket connect error ip:" + ip + ",port:" + port + ",Exception:" +e.getMessage());58 }59 log.debug("Exit Method:connect()");60 }61

62 public void write(byte[] msg, int len) throwsIOException {63 log.trace("dataOutputStream.write");64 dataOutputStream.write(msg, 0, len);65 log.trace("dataOutputStream.flush");66 dataOutputStream.flush();67 updateUseDate();68 }69

70 public byte[] read(int bufferSize, int timeOut) throwsIOException {71 socket.setSoTimeout(timeOut * 1000);72 byte[] bytes = new byte[bufferSize];73 log.trace("dataInputStream.read");74 int len =dataInputStream.read(bytes);75 updateUseDate();76 log.debug("readLen:" +len);77 byte[] tempBytes = null;78 if (len > 0) {79 tempBytes = new byte[len];80 System.arraycopy(bytes, 0, tempBytes, 0, len);81 }82 returntempBytes;83 }84

85 public voidclose() {86 log.debug("Entry Method:close()");87 try{88 if (null !=dataOutputStream) {89 dataOutputStream.close();90 }91 if (null !=dataInputStream) {92 dataInputStream.close();93 }94 if (null != socket && !socket.isClosed()) {95 socket.close();96 }97 socket = null;98 } catch(IOException e) {99 log.error("SocketClient close Exception:" +e.getMessage());100 }101 log.debug("Exit Method:close()");102 }103

104 public boolean valid() throwsException {105 if (null == socket || socket.isClosed() ||

106 socket.isInputShutdown() ||socket.isOutputShutdown()) {107 if (dataInputStream != null) {108 dataInputStream.close();109 }110 if (dataOutputStream != null) {111 dataOutputStream.close();112 }113 if (socket != null) {114 socket.close();115 }116 return false;117 }118 return true;119 }120

121 public longgetTimePass() {122 log.trace("Entry Method:getTimePass(),useDate:{}", useDate.getTime());123 Date date = newDate();124 log.debug("Exit Method:getTimePass(),timePass:{}", date.getTime() -useDate.getTime());125 return (date.getTime() -useDate.getTime());126 }127

128 public voidupdateUseDate() {129 useDate = newDate();130 }131

132 public static voidmain(String[] args) {133

134 System.out.println("SocketClient main start");135 try{136 System.out.println("----------try start----------");137 SocketClient socketClient = new SocketClient("localhost", 8080);138 socketClient.connect();139 String strInput = "hello server !";140 socketClient.write(strInput.getBytes(), strInput.length());141 byte[] recv = socketClient.read(1024, 10);142 String strOriginal = null;143 if (null !=recv) {144 strOriginal = newString(recv, StandardCharsets.ISO_8859_1);145 }146 log.info("strOriginal:" +strOriginal);147

148 System.out.println("----------try end----------");149 } catch(Exception e) {150 System.out.println("catch error:" +e.getMessage());151 e.printStackTrace();152 }153 System.out.println("SocketClient main end");154 }155

156 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值