Home> Java> javaTutorial> body text

How to write code to implement communication client using Socket in Java

PHPz
Release: 2023-04-25 08:52:06
forward
906 people have browsed it

The specific client code is as follows:

  1. import java.net.*;

  2. import java.io.*;

  3. import org.apache.log4j.Logger;

  4. public class SocketClient {

  5. static Logger log = Logger.getLogger(SocketClient.class.
    getName()); //日志记录信息

  6. private String hostName;

  7. private int portNum;

  8. private int delaySecond; // 发文接收返回报文延时

  9. public SocketClient() {

  10. this.hostName = "192.168.0.1";

  11. this.portNum = 7000;

  12. this.delaySecond = 50000;

  13. pFileOp = null;

  14. }

  15. private Socket getSocket() {

  16. Socket socket = null;

  17. try {

  18. socket = new Socket(hostName, portNum);

  19. } catch (UnknownHostException e) {

  20. System.out.println("-->未知的主机名:" + hostName + " 异常");

  21. } catch (IOException e) {

  22. System.out.println("-hostName=" + hostName + " portNum="

  23. + portNum + "---->IO异常错误" + e.getMessage());

  24. }

  25. return socket;

  26. }

  27. public String sendMessage(String strMessage) {

  28. String str = "";

  29. String serverString = "";

  30. Socket socket;

  31. try {

  32. socket = getSocket();

  33. // socket.setKeepAlive(true);

  34. if (socket == null) { // 未能得到指定的Socket对象,Socket通讯为空

  35. return "0001";

  36. }

  37. PrintWriter out = new PrintWriter(socket.getOutputStream());

  38. //log.info("---->发送报文="+strMessage);

  39. out.println(strMessage);

  40. out.flush();

  41. BufferedReader in = new BufferedReader(new InputStreamReader(

  42. socket.getInputStream()));

  43. long sendTime = System.currentTimeMillis();

  44. long receiveTime = System.currentTimeMillis();

  45. boolean received = false; // 成功接收报文

  46. boolean delayTooLong = false;

  47. serverString = null;

  48. while (!received && !delayTooLong) {

  49. if (socket.getInputStream().available() > 0) {

  50. // serverString = in.readLine();

  51. char tagChar[];

  52. tagChar = new char[1024];

  53. int len;

  54. String temp;

  55. String rev = "";

  56. if ((len = in.read(tagChar)) != -1) {

  57. temp = new String(tagChar, 0, len);

  58. rev += temp;

  59. temp = null;

  60. }

  61. serverString = rev;

  62. }

  63. receiveTime = System.currentTimeMillis();

  64. if (serverString != null)

  65. received = true; // 字符串不为空,接收成功

  66. if ((receiveTime - sendTime) > delaySecond)

  67. delayTooLong = true; // 接收等待时间过长,超时

  68. }

  69. in.close();

  70. out.close();

  71. str=serverString;

  72. if (delayTooLong) str="2190"; //超时标志为真,返回超时码

  73. if (!received) str ="2190";

  74. socket.close();

  75. } catch (UnknownHostException e) {

  76. log.error("---->出现未知主机错误! 主机信息=" + this.hostName +
    " 端口号="

  77. + this.portNum + " 出错信息=" + e.getMessage());

  78. str = "2191";

  79. // System.exit(1);

  80. } catch (IOException e) {

  81. log.error("---->出现IO异常! 主机信息=" + this.hostName +
    " 端口号="

  82. + this.portNum + " 出错信息=" + e.getMessage());

  83. e.printStackTrace();

  84. str = "2191";

  85. } catch (Exception e) {

  86. str="2177";

  87. log.error("---->出现未知异常" + e.getMessage());

  88. } finally {

  89. socket = null;

  90. str.trim();

  91. //log.info("--->返回的socket通讯字符串="+str);

  92. return str;

  93. }

  94. }

  95. }

Copy after login

The above is the detailed content of How to write code to implement communication client using Socket in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!