【问题标题】:Client And Server Socket Connection using C#使用 C# 的客户端和服务器套接字连接
【发布时间】:2016-03-10 05:59:00
【问题描述】:

我创建了两个项目,一个带有客户端,另一个带有服务器,以在它们之间交换文本;在同一台计算机上我运行这些 exe。 我的客户端连接代码连接看起来:

 using (SocketClient sa = new SocketClient(host, port))   
    {   
    sa.Connect();   
    Console.WriteLine(sa.SendReceive("Message #" + i.ToString()));   
    }   
    sa.Disconnect();     

虽然 socketclient 是我的类,其中包含这些方法和构造函数:

internal SocketClient(String hostName, Int32 port)   
{   
IPHostEntry host = Dns.GetHostEntry(hostName);    
IPAddress[] addressList = host.AddressList;      
this.hostEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);     
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily,      SocketType.Stream, ProtocolType.Tcp);    
}      
internal void Connect()    
{     
SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs();    
connectArgs.UserToken = this.clientSocket;    
connectArgs.RemoteEndPoint = this.hostEndPoint;     
connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);     
 clientSocket.ConnectAsync(connectArgs);     
 autoConnectEvent.WaitOne();     
SocketError errorCode = connectArgs.SocketError;     
 if (errorCode != SocketError.Success)     
{   
throw new SocketException((Int32)errorCode);     
}      
}      
internal void Disconnect()     
{    
 clientSocket.Disconnect(false);     
 }     
private void OnConnect(object sender, SocketAsyncEventArgs e)    
 {     
 autoConnectEvent.Set();    
 this.connected = (e.SocketError == SocketError.Success);    
 }     
internal String SendReceive(String message)    
{    
 if (this.connected)     
{     
Byte[] sendBuffer = Encoding.ASCII.GetBytes(message);      
SocketAsyncEventArgs completeArgs = new SocketAsyncEventArgs();     
 completeArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);   
 completeArgs.UserToken = this.clientSocket;   
  completeArgs.RemoteEndPoint = this.hostEndPoint;   
  completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);     
 clientSocket.SendAsync(completeArgs);    
  AutoResetEvent.WaitAll(autoSendReceiveEvents);      
return Encoding.ASCII.GetString(completeArgs.Buffer,    completeArgs.Offset,completeArgs.BytesTransferred);     
}   
else    
{       
throw new SocketException((Int32)SocketError.NotConnected);     
}     
}   

在服务器端代码看起来像这样:

SocketListener sl = new SocketListener(numConnections, bufferSize);     
sl.Start(port);     
Console.WriteLine("Server listening on port {0}.   
Press any key to terminate the server process...", port);       
Console.Read();       
sl.Stop();    

Socket 监听器是我的类,它包含这个方法和构造函数:

internal SocketListener(Int32 numConnections, Int32 bufferSize)    
 {     
  this.numConnectedSockets = 0;  
  this.numConnections = numConnections;  
 this.bufferSize = bufferSize;      
 this.readWritePool = new SocketAsyncEventArgsPool(numConnections);     
 this.semaphoreAcceptedClients = new Semaphore(numConnections, numConnections);      
 for (Int32 i = 0; i < this.numConnections; i++)     
{     
SocketAsyncEventArgs readWriteEventArg = new SocketAsyncEventArgs();     
readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs> (OnIOCompleted);      
readWriteEventArg.SetBuffer(new Byte[this.bufferSize], 0, this.bufferSize);    
this.readWritePool.Push(readWriteEventArg);    
}       
}  
internal void Start(Int32 port)   
{     
 IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;     
IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);     
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);     
this.listenSocket.ReceiveBufferSize = this.bufferSize;      
            this.listenSocket.SendBufferSize = this.bufferSize;     
if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)     
{     
this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);     
this.listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));     
}     
else     
{     
this.listenSocket.Bind(localEndPoint);    
}    
this.listenSocket.Listen(this.numConnections);     
this.StartAccept(null);      
 mutex.WaitOne();     
}     

我的路由器已经有了端口转发,因为服务器端 exe 在没有端口转发的情况下无法侦听。
在家里的同一台电脑和同一端口上发送和接收工作正常。
当我尝试在我的办公室计算机上运行这两个代码 exe 时,它​​会在以下行引发异常:

Exception thrown by socket

谁能指导我这是什么问题以及如何解决它?
谢谢

【问题讨论】:

    标签: c# client-server serversocket tcplistener asyncsocket


    【解决方案1】:

    您是否尝试过暂时禁用 Windows 防火墙?

    【讨论】:

    • 我不能,因为我办公室里有一台由网络工程师操作的服务器,我不能告诉他这样做,因为这会是安全问题。我也可能认为这是防火墙阻止我不能通过一些代码逻辑来解决问题...任何来源...谢谢
    • 您可以尝试使用端口 80 而不是自定义端口,以查看它们是否打开。
    • 我尝试使用该端口,但它响应该端口已在使用中
    • 自从您第一次在本地尝试以来,您没有多台计算机在没有公司安全的情况下测试它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 2021-03-31
    • 2019-03-17
    • 2017-05-26
    • 2014-03-10
    相关资源
    最近更新 更多