通过Java套接字监听端口 [英] Listen to port via a Java socket
问题描述
我的客户端与之通信的服务器软件会定期在端口4000上发送事务消息.我需要将这些消息逐行打印到控制台.(最终,我将不得不将这些值写入表中,但我将其保存以备后用.)
A server software my client communicates with regularly sends transaction messages on port 4000. I need to print those messages to the console line by line. (Eventually I will have to write those values to a table, but I’m saving that for later.)
我尝试了此代码,但未输出任何内容:
I tried this code but it doesn’t output anything:
package merchanttransaction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MerchantTransaction {
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket("192.168.1.104", 4000);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
顺便说一句,我需要能够监视该端口,直到程序终止.我不确定上面的代码是否能够做到这一点,因为我看不到代码的任何迭代.
By the way, I need to be able to monitor that port until the program terminates. I’m not sure if the code above will be able to do that because I don’t see any iteration to the code.
我正在使用在Ubuntu上运行的Java版本1.6.0_24,SE运行时环境(内部版本1.6.0_24-b07).
I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.
推荐答案
您需要使用 ServerSocket
.您可以在此处找到说明.
You need to use a ServerSocket
. You can find an explanation here.
这篇关于通过Java套接字监听端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!