Java中怎么利用Socket实现一个通讯客户端
本篇文章给大家分享的是有关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实现一个通讯客户端,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网行业资讯频道。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341