本篇文章给大家分享的是有关Java中怎么利用Socket实现一个通讯客户端,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
具体客户端代码如下:
import java.net.*;
import java.io.*;
import org.apache.log4j.Logger;
public class SocketClient {
static Logger log = Logger.getLogger(SocketClient.class.
getName()); //日志记录信息private String hostName;
private int portNum;
private int delaySecond; // 发文接收返回报文延时
public SocketClient() {
this.hostName = "192.168.0.1";
this.portNum = 7000;
this.delaySecond = 50000;
pFileOp = null;
}
private Socket getSocket() {
Socket socket = null;
try {
socket = new Socket(hostName, portNum);
} catch (UnknownHostException e) {
System.out.println("-->未知的主机名:" + hostName + " 异常");
} catch (IOException e) {
System.out.println("-hostName=" + hostName + " portNum="
+ portNum + "---->IO异常错误" + e.getMessage());
}
return socket;
}
public String sendMessage(String strMessage) {
String str = "";
String serverString = "";
Socket socket;
try {
socket = getSocket();
// socket.setKeepAlive(true);
if (socket == null) { // 未能得到指定的Socket对象,Socket通讯为空
return "0001";
}
PrintWriter out = new PrintWriter(socket.getOutputStream());
//log.info("---->发送报文="+strMessage);
out.println(strMessage);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
long sendTime = System.currentTimeMillis();
long receiveTime = System.currentTimeMillis();
boolean received = false; // 成功接收报文
boolean delayTooLong = false;
serverString = null;
while (!received && !delayTooLong) {
if (socket.getInputStream().available() > 0) {
// serverString = in.readLine();
char tagChar[];
tagChar = new char[1024];
int len;
String temp;
String rev = "";
if ((len = in.read(tagChar)) != -1) {
temp = new String(tagChar, 0, len);
rev += temp;
temp = null;
}
serverString = rev;
}
receiveTime = System.currentTimeMillis();
if (serverString != null)
received = true; // 字符串不为空,接收成功
if ((receiveTime - sendTime) > delaySecond)
delayTooLong = true; // 接收等待时间过长,超时
}
in.close();
out.close();
str=serverString;
if (delayTooLong) str="2190"; //超时标志为真,返回超时码
if (!received) str ="2190";
socket.close();
} catch (UnknownHostException e) {
log.error("---->出现未知主机错误! 主机信息=" + this.hostName +
" 端口号="+ this.portNum + " 出错信息=" + e.getMessage());
str = "2191";
// System.exit(1);
} catch (IOException e) {
log.error("---->出现IO异常! 主机信息=" + this.hostName +
" 端口号="+ this.portNum + " 出错信息=" + e.getMessage());
e.printStackTrace();
str = "2191";
} catch (Exception e) {
str="2177";
log.error("---->出现未知异常" + e.getMessage());
} finally {
socket = null;
str.trim();
//log.info("--->返回的socket通讯字符串="+str);
return str;
}
}
}
以上就是Java中怎么利用Socket实现一个通讯客户端,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。