套接字客户端连接

时间:2014-12-10 15:05:35

标签: sockets networking client

我正在尝试学习如何在java中使用套接字 我输入了来自Tutorials point的示例,但我无法使其正常工作(套接字客户端示例)。 我做的唯一改变是,而不是采取端口&从args传入的主机名,我正在硬编码端口并获取本地主机。我的代码如下

import java.net.*;
import java.io.*;

public class GreetClient
{
   public static void main(String [] args)
   {
      InetAddress lHost=null;
      try { lHost = InetAddress.getLocalHost(); }
      catch(Exception e) { System.out.println("Local Host Error");}
      int port = 1234;
      try
      {
         System.out.println("Connecting to " + lHost + " on port " + port);
         Socket client = new Socket(lHost, port);
         System.out.println("Just connected to " + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);

         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("Server says " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

我得到的错误是:

Connecting to Bridgets_laptop/192.168.56.1 on port 1234
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:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at java.net.Socket.<init>(Socket.java:425)
    at java.net.Socket.<init>(Socket.java:241)
    at GreetClient.main(GreetClient.java:27)

我出错的任何想法?

1 个答案:

答案 0 :(得分:1)

&#34;连接被拒绝&#34; -part听起来像你有防火墙阻止你自己的应用程序进入Socket1234或你没有打开ServerSocket 1234连接到。

可以使用

连接到ServerSocket
telnet 127.0.0.1 1234

如果您使用Windows?