如何用JAVA代码监听某个开放端口
1个回答
展开全部
比如我要监听1234这个端口,代码如下:
String ip = "127.0.0.1";
int port = 1234;
try {
Socket socket = new Socket(ip, port);
socket.setSoTimeout(5539900);
java.io.OutputStream out = socket.getOutputStream();
byte[] date = "hello world".getBytes();
out.write(data);
out.flush();
byte[] buffer = new byte[1024];
int len = -1;
java.io.FileOutputStream fout = new java.io.FileOutputStream(
"d:/response.txt");
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.InputStream in = socket.getInputStream();
while ((len = in.read(buffer, 0, buffer.length)) > 0) {
bout.write(buffer, 0, len);
}
in.close();
bout.flush();
bout.close();
byte[] rdata = bout.toByteArray();
System.out.println(new String(rdata));
fout.write(rdata);
fout.flush();
fout.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器端的
ServerSocket ss = new ServerSocket(1234);
Socket socket=null;
BufferedReader in;
PrintWriter out;
while (true) {
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
String line = in.readLine();
out.println("you input is :" + line);
out.close();
in.close();
socket.close();
}
String ip = "127.0.0.1";
int port = 1234;
try {
Socket socket = new Socket(ip, port);
socket.setSoTimeout(5539900);
java.io.OutputStream out = socket.getOutputStream();
byte[] date = "hello world".getBytes();
out.write(data);
out.flush();
byte[] buffer = new byte[1024];
int len = -1;
java.io.FileOutputStream fout = new java.io.FileOutputStream(
"d:/response.txt");
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.InputStream in = socket.getInputStream();
while ((len = in.read(buffer, 0, buffer.length)) > 0) {
bout.write(buffer, 0, len);
}
in.close();
bout.flush();
bout.close();
byte[] rdata = bout.toByteArray();
System.out.println(new String(rdata));
fout.write(rdata);
fout.flush();
fout.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器端的
ServerSocket ss = new ServerSocket(1234);
Socket socket=null;
BufferedReader in;
PrintWriter out;
while (true) {
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
String line = in.readLine();
out.println("you input is :" + line);
out.close();
in.close();
socket.close();
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
Storm代理
2023-07-25 广告
2023-07-25 广告
StormProxies是一家国内优质海外HTTP代理商,拥有一个庞大的IP资源池,覆盖200多个地区,IP数量大且匿名度高。其优点还包括超高并发、稳定高效、技术服务等特点,同时提供HTTP、HTTPS以及SOCKS5协议支持。此外,Sto...
点击进入详情页
本回答由Storm代理提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询