套接字创建例外

时间:2014-11-13 01:47:07

标签: java sockets

我有一点技术问题。我想在localhost上使用Java Socket读取数据。数据将由外部模拟器连续发送。只是为了测试我写了小代码,但有例外。我不确定为什么会产生这种异常,因为每件事情都很好。

public class ReceiveFromSocket {
public static void main(String[] args) throws IOException {
    Socket socket = new Socket("localhost", 3333);
    DataInputStream in;
    while (true) {
        try {
            socket.setSoTimeout(5000);
            in = new DataInputStream(socket.getInputStream());
            System.out.println(in.readUTF());
        } catch (Exception e) {

        }
    }
  }

}

当我运行它时,我收到以下错误

Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at data.ReceiveFromSocket.main(ReceiveFromSocket.java:27)
Java Result: 1

任何人都可以指出我所缺少的东西。

1 个答案:

答案 0 :(得分:0)

  

模拟器是使用UDP协议发送数据

您的代码正在使用TCP协议。请查看DatagramSocket而不是Socket。根据我的评论忘掉readUTF()