这篇文章主要介绍了Java利用Socket实现通讯客户端的代码怎么写的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Java利用Socket实现通讯客户端的代码怎么写文章都会有所收获,下面我们一起来看看吧。
创新互联是一家做网站、网站建设,提供网页设计,网站设计,网站制作,建网站,按需定制制作,网站开发公司,于2013年开始是互联行业建设者,服务者。以提升客户品牌价值为核心业务,全程参与项目的网站策划设计制作,前端开发,后台程序制作以及后期项目运营并提出专业建议和思路。
具体客户端代码如下:
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实现通讯客户端的代码怎么写”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Java利用Socket实现通讯客户端的代码怎么写”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。