使用C#进行客户端和服务器套接字连接

时间:2016-03-10 05:59:00

标签: c# client-server serversocket tcplistener asyncsocket

我创建了两个项目,一个是客户端,另一个是服务器,用于在两个项目之间交换文本;在同一台计算机上运行这些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();    

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

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没有端口转发而没有收听,我已经将我的路由器移植到了前面。
    它在家里用同一台PC和同一个端口发送和接收工作正常     当我尝试在我的办公室计算机上运行两个代码exe时,它会在以下行引发异常:

Exception thrown by socket

任何人都可以指导我这个问题以及解决方法吗? 谢谢

1 个答案:

答案 0 :(得分:0)

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