Socket.Accept() Method
public Socket Accept(// optional);
Summary
Accepts an incoming connection request and creates a new Socket to handle a remote host connection.
Returns
A new Socket object that represents the accepted connection. The created Socket is a copy of the original Socket, SocketOptions, and default timeouts. Use the new Socket to receive and send data to the remote host.
Exceptions
- ObjectDisposedException: The
Sockethas been closed. - SocketException: An error occurred when attempting to access the socket.
Remarks
The Accept method is used by connection-oriented protocols, such as TCP, to accept incoming connection requests.
Before calling Accept, you must first Bind the Socket to a local endpoint and then call Listen to put the socket into listening state.
The Accept method blocks until a connection is established.
If you need to accept connections asynchronously, use the AcceptAsync method.
Example
using System; using System.Net; using System.Net.Sockets; using System.Text; public class SimpleServer { public static void Main(string[] args) { int port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); using (Socket listener = new Socket(localAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind( new IPEndPoint(localAddr, port) ); listener.Listen(10); Console.WriteLine("Waiting for a connection..."); while (true) { Socket handler = listener.Accept(); Console.WriteLine("Connection accepted from {0}", handler.RemoteEndPoint); // Process the connection here, e.g., receive data byte[] bytes = new Byte[1024]; int bytesRec = handler.Receive(bytes); Console.WriteLine("Received : {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); // Echo back to client byte[] msg = Encoding.ASCII.GetBytes("Echo: " + Encoding.ASCII.GetString(bytes, 0, bytesRec)); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } } }