How to write code to implement communication client using Socket in Java
The specific client code is as follows:
<ol class=" list-paddingleft-2"> <li><p>import java.net.*; </p></li> <li><p>import java.io.*; </p></li> <li><p>import org.apache.log4j.Logger; </p></li> <li><p>public class SocketClient { </p></li> <li><p>static Logger log = Logger.getLogger(SocketClient.class.<br>getName()); //日志记录信息 </p></li> <li><p>private String hostName; </p></li> <li><p>private int portNum; </p></li> <li><p>private int delaySecond; // 发文接收返回报文延时 </p></li> <li><p>public SocketClient() { </p></li> <li><p>this.hostName = "192.168.0.1"; </p></li> <li><p>this.portNum = 7000; </p></li> <li><p>this.delaySecond = 50000; </p></li> <li><p>pFileOp = null; </p></li> <li><p>} </p></li> <li><p>private Socket getSocket() { </p></li> <li><p>Socket socket = null; </p></li> <li><p>try { </p></li> <li><p>socket = new Socket(hostName, portNum); </p></li> <li><p>} catch (UnknownHostException e) { </p></li> <li><p>System.out.println("-->未知的主机名:" + hostName + " 异常"); </p></li> <li><p>} catch (IOException e) { </p></li> <li><p>System.out.println("-hostName=" + hostName + " portNum=" </p></li> <li><p>+ portNum + "---->IO异常错误" + e.getMessage()); </p></li> <li><p>} </p></li> <li><p>return socket; </p></li> <li><p>} </p></li> <li><p>public String sendMessage(String strMessage) { </p></li> <li><p>String str = ""; </p></li> <li><p>String serverString = ""; </p></li> <li><p>Socket socket; </p></li> <li><p>try { </p></li> <li><p>socket = getSocket(); </p></li> <li><p>// socket.setKeepAlive(true); </p></li> <li><p>if (socket == null) { // 未能得到指定的Socket对象,Socket通讯为空 </p></li> <li><p>return "0001"; </p></li> <li><p>} </p></li> <li><p>PrintWriter out = new PrintWriter(socket.getOutputStream()); </p></li> <li><p>//log.info("---->发送报文="+strMessage); </p></li> <li><p>out.println(strMessage); </p></li> <li><p>out.flush(); </p></li> <li><p>BufferedReader in = new BufferedReader(new InputStreamReader( </p></li> <li><p>socket.getInputStream())); </p></li> <li><p>long sendTime = System.currentTimeMillis(); </p></li> <li><p>long receiveTime = System.currentTimeMillis(); </p></li> <li><p>boolean received = false; // 成功接收报文 </p></li> <li><p>boolean delayTooLong = false; </p></li> <li><p>serverString = null; </p></li> <li><p>while (!received && !delayTooLong) { </p></li> <li><p>if (socket.getInputStream().available() > 0) { </p></li> <li><p>// serverString = in.readLine(); </p></li> <li><p>char tagChar[]; </p></li> <li><p>tagChar = new char[1024]; </p></li> <li><p>int len; </p></li> <li><p>String temp; </p></li> <li><p>String rev = ""; </p></li> <li><p>if ((len = in.read(tagChar)) != -1) { </p></li> <li><p>temp = new String(tagChar, 0, len); </p></li> <li><p>rev += temp; </p></li> <li><p>temp = null; </p></li> <li><p>} </p></li> <li><p>serverString = rev; </p></li> <li><p>} </p></li> <li><p>receiveTime = System.currentTimeMillis(); </p></li> <li><p>if (serverString != null) </p></li> <li><p>received = true; // 字符串不为空,接收成功 </p></li> <li><p>if ((receiveTime - sendTime) > delaySecond) </p></li> <li><p>delayTooLong = true; // 接收等待时间过长,超时 </p></li> <li><p>} </p></li> <li><p>in.close(); </p></li> <li><p>out.close(); </p></li> <li><p>str=serverString; </p></li> <li><p>if (delayTooLong) str="2190"; //超时标志为真,返回超时码 </p></li> <li><p>if (!received) str ="2190"; </p></li> <li><p>socket.close(); </p></li> <li><p>} catch (UnknownHostException e) { </p></li> <li><p>log.error("---->出现未知主机错误! 主机信息=" + this.hostName + <br>" 端口号=" </p></li> <li><p>+ this.portNum + " 出错信息=" + e.getMessage()); </p></li> <li><p>str = "2191"; </p></li> <li><p>// System.exit(1); </p></li> <li><p>} catch (IOException e) { </p></li> <li><p>log.error("---->出现IO异常! 主机信息=" + this.hostName + <br>" 端口号=" </p></li> <li><p>+ this.portNum + " 出错信息=" + e.getMessage()); </p></li> <li><p>e.printStackTrace(); </p></li> <li><p>str = "2191"; </p></li> <li><p>} catch (Exception e) { </p></li> <li><p>str="2177"; </p></li> <li><p>log.error("---->出现未知异常" + e.getMessage()); </p></li> <li><p>} finally { </p></li> <li><p>socket = null; </p></li> <li><p>str.trim(); </p></li> <li><p>//log.info("--->返回的socket通讯字符串="+str); </p></li> <li><p>return str; </p></li> <li><p>} </p></li> <li><p>} </p></li> <li><p>} </p></li> </ol>
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!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
