套接字异常错误

时间:2018-03-19 05:39:02

标签: c# .net sockets exception

我在C#.net中有一个网络套接字程序。 我必须连接ip:169.254.74.65和端口:7998,我的IP是:169.254.74.63。 所以我有这个代码:

using System;
using System.Net;
using System.Net.Sockets;

class MyTcpListener{
   public static void Main(){
       TcpListener server = null;
         try{
             Int32 port = 7998;
             IPAddress localAddr = IPAddress.Parse("169.254.74.65");
             server = new TcpListener(localAddr, port);
             server.Start();
             Byte[] bytes = new Byte[500];
             String data = null;
             while (true){
             Console.Write("Waiting for a connection... ");
             TcpClient client = server.AcceptTcpClient();
             data = null;
             NetworkStream stream = client.GetStream();
             int i;
             while ((i = stream.Read(bytes, 0, bytes.Length)) != 0){
             data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
             Console.WriteLine("Received: {0}", data);
             }
             client.Close();}
          }
        catch (SocketException e){
        Console.WriteLine("SocketException: {0}", e);}
        finally{ server.Stop();  }

Ping在两个IP之间正常工作。甚至telnet 169.254.74.65 7998给了我正确的结果并听取了正确的消息。所以连接很稳固。 但是当我运行上面的代码时,它显示了一个异常:

> SocketException: System.Net.Sockets.SocketException (0x80004005): The requested address is not valid in its context
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at System.Net.Sockets.TcpListener.Start()
   at MyTcpListener.Main() in C:\Users\Administrator\source\repos\TCPListener\TCPListener\Program.cs:line 12

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

您的代码适合我:

您是否真的从客户端套接字代码以127.0.0.1:7998命中服务器?

enter image description here

<强>更新 所以你的服务器IP是169.xx.xx.65,而你自己的DEV机器IP是169.xx.xx.63 您的代码是创建TCP服务器连接的代码。虽然(如果我没错) - 你只需要连接到那台HL7机器。

了解HL7机器将是服务器,您的机器将是客户端。所以你只需要TcpClient。类似的东西:

TcpClient client = new TcpClient("169.xx.xx.65", 7998);

使用Connect / GetStream等方法:https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx