package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class socket {
public static void main(String[] args) throws IOException, InterruptedException {
//客户端请求与平台建立TCP连接
Socket client = new Socket("0.0.0.0", 9900);
client.setSoTimeout(7000);
//获取Socket的输出流,用来发送数据到服务端
PrintStream out = new PrintStream(client.getOutputStream());
//获取Socket的输入流,用来接收从服务端发送过来的数据
BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean flag = true;
while(flag){
//System.out.print("输入信息:");
//String str = input.readLine();
String str = "00009b08d5ca3553d9172f464312b6db00140003";
//发送数据到服务端
byte []buf1 = new byte[20];
for(int i=0;i<20;i++){
//将字符串转为16进制输出
buf1[i] = (byte) Integer.parseInt(str.substring(i*2, i*2+2),16);
//System.out.println(str.substring(i*2, i*2+2));
}
//System.out.println();
try {
//发送字节
out.write(buf1, 0, buf1.length);
System.out.println("发送");
} catch (Exception e) {
System.out.println("失败");
}
if("bye".equals(str)){
flag = false;
System.out.println("失败");
}else{
// try{
// //从服务器端接收数据有个时间限制(系统自设,也可以自己设置),超过了这个时间,便会抛出该异常
// String echo = buf.readLine();
// System.out.println(echo);
// }catch(SocketTimeoutException e){
// System.out.println("Time out, No response");
// }
}
//每隔10秒发送一次数据
Thread.sleep(10000);
}
input.close();
if(client != null){
//如果构造函数建立起了连接,则关闭套接字,如果没有建立起连接,自然不用关闭
client.close(); //只关闭socket,其关联的输入输出流也会被关闭
}
}
}
自己写的socket通信代码
最新推荐文章于 2022-11-14 16:17:00 发布