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

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

Apr 25, 2023 am 08:52 AM
java socket

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>
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles