【发布时间】:2014-07-11 19:13:53
【问题描述】:
这是我的客户
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
try
{
sck.Connect(localEndpoint);
}
catch (Exception ex)
{
Console.Write("Unable to connect local endpoint! \r\n ");
Main(args);
}
string text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Console.Write("Data sent ! \r\n");
Console.Write("Press any key to continue...");
Console.Read();
sck.Close();
}
这是我的服务器。
static byte[] Buffer { get; set; }
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(IPAddress.Any, 1234));
sck.Listen(100);
Socket accepted = sck.Accept();
Buffer = new byte[accepted.ReceiveBufferSize];
int byteReades = accepted.Receive(Buffer);
byte[] formatted = new byte[byteReades];
for (int i = 0; i < byteReades; i++)
{
formatted[i] = Buffer[i];
}
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");
sck.Close();
accepted.Close();
Console.ReadKey();
}
当我尝试运行客户端以向服务器发送数据时,我遇到了 SocketException "Connection is not established on 127.0.0.1 :1234" 。错误代码为 10061。 请帮助解决这个问题。
【问题讨论】:
-
我复制了您在 2 个新的控制台应用程序中提供的代码。一个用于客户端,一个用于服务器。他们都工作 100% 罚款。问题很可能是你的问题。也许是防火墙设置。但是代码可以正常工作。
-
您在哪一行得到异常?
-
我认为您的防火墙阻止了端口 1234... 错误 10061 是“连接被拒绝”错误。
-
感谢您的回答,我认为您对防火墙设置的问题是正确的,但我需要在该设置中进行更改。
-
在这条线上。 sck.Connect(localEndpoint);