简体   繁体   中英

Client And Server Socket Connection using C#

I created two projects one with client and other with server to exchange text between both of them;on same computer i run those exe. MY Client Side Connection Code connection looked :

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

while socketclient is my class which contain these methods and constructor:

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);     
}     
}   

while on server side code looks like that:

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 listener is my class which contain this method and constructor :

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();     
}     

I have already port forward of my router because of server side exe which didn't listen without port forwarding.
it is working fine with send and receive on same pc and same port at home.
While when i try to run both of codes exe on my office computer it throws exception at following line:

Exception thrown by socket

Could any one guide me whats the problem and how to resolve it ?
Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM