【发布时间】:2013-03-03 17:29:59
【问题描述】:
我是 C# 中套接字编程的新手。疯狂地在网上搜索我的问题的解决方案,但没有找到任何可以解决它的方法。所以这是我的问题:
我正在尝试编写客户端-服务器应用程序。目前,服务器也将在我的本地机器上运行。应用程序将数据的字节流从客户端传输到服务器。 问题是服务器没有检测到客户端的连接请求,而客户端能够连接并传输字节流。
这是服务器代码:
String strHostName = Dns.GetHostName();
Console.WriteLine(strHostName);
IPAddress ip = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(ip, port);
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
soc.Bind(ipEnd);
Console.WriteLine("Web Server Running... Press ^C to Stop...");
Thread th = new Thread(new ThreadStart(StartListen));
th.Start();
StartListen线程如下:
public void StartListen()
{
try
{
while (true)
{
string message;
Byte[] bSend = new Byte[1024];
soc.Listen(100);
if (soc.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\n CLient IP {0}\n", soc.RemoteEndPoint);
Byte[] bReceive = new Byte[1024 * 5000];
int i = soc.Receive(bReceive);
客户端代码如下:
hostIPAddress = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(hostIPAddress,port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Console.WriteLine("Connecting to Server...");
clientSocket.Connect(ipEnd);
Console.WriteLine("Sending File...");
clientSocket.Send(clientData);
Console.WriteLine("Disconnecting...");
clientSocket.Close();
Console.WriteLine("File Transferred...");
现在发生的情况是服务器启动,当我运行客户端时,它会连接、发送和关闭。但是服务器控制台上什么也没有发生,它没有检测到任何连接:if (soc.Connected) 仍然为 false。
我通过 netstat 检查了服务器是否在监听 127.0.0.1:5050,它确实在监听。想不通问题所在。请帮忙。
【问题讨论】:
标签: c# sockets client-server