本文整理汇总了C#中Socket.Accept方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Accept方法的具体用法?C# Socket.Accept怎么用?C# Socket.Accept使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Socket
的用法示例。
在下文中一共展示了Socket.Accept方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Socket_SendReceive_Success
public void Socket_SendReceive_Success()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
client.Connect(endPoint);
using (Socket accepted = server.Accept())
{
var data = new byte[1];
for (int i = 0; i < 10; i++)
{
data[0] = (byte)i;
accepted.Send(data);
data[0] = 0;
Assert.Equal(1, client.Receive(data));
Assert.Equal(i, data[0]);
}
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
示例2: send
//static void Main(string[] args, int a)
public static void send()
{
String name = Id.name;
String a2 = link.a.ToString();
int y = 9;
String a3 = y.ToString();
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 23));
sck.Listen(0);
Socket acc = sck.Accept();
// all the data will be sent in one buffer.
byte[] buffer = Encoding.Default.GetBytes(name + a2 + a3);
acc.Send(buffer, 0, buffer.Length, 0);
buffer = new byte[255];
int rec = acc.Receive(buffer, 0, buffer.Length, 0);
Array.Resize(ref buffer, rec);
Console.WriteLine("Received: {0}", Encoding.Default.GetString(buffer));
sck.Close();
acc.Close();
Console.Read();
}
示例3: Main
// main.. how we start it all up
static int Main(string[] args)
{
// args checker
if (args.Length != 4)
{
System.Console.WriteLine("port_redir.exe <listenIP> <listenPort> <connectIP> <connectPort>");
return 1;
}
// Our socket bind "function" we could just as easily replace this with
// A Connect_Call and make it a true gender-bender
IPEndPoint tmpsrv = new IPEndPoint(IPAddress.Parse(args[0]), Int32.Parse(args[1]));
Socket ipsrv = new Socket(tmpsrv.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ipsrv.Bind(tmpsrv);
ipsrv.Listen(10);
// loop it so we can continue to accept
while (true)
{
try
{
// block till something connects to us
Socket srv = ipsrv.Accept();
// Once it does connect to the outbound ip:port
Socket con = Connect_Call(args[2], Int32.Parse(args[3]));
// Read and write back and forth to our sockets.
Thread SrvToCon = new Thread(() => Sock_Relay(srv, con));
SrvToCon.Start();
Thread ConToSrv = new Thread(() => Sock_Relay(con, srv));
ConToSrv.Start();
}
catch (Exception e) { Console.WriteLine("{0}", e); }
}
}
示例4: Main
static void Main (string [] args)
{
byte [] buffer = new byte [10];
IPAddress ipAddress = IPAddress.Loopback;
IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 12521);
Socket listener = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
listener.Bind (localEndPoint);
listener.Listen (5);
Socket handler = listener.Accept ();
int bytesRec = handler.Receive (buffer, 0, 10, SocketFlags.None);
string msg = Encoding.ASCII.GetString (buffer, 0, bytesRec);
if (msg != "hello") {
string dir = AppDomain.CurrentDomain.BaseDirectory;
using (StreamWriter sw = File.CreateText (Path.Combine (dir, "error"))) {
sw.WriteLine (msg);
}
}
handler.Close ();
Thread.Sleep (200);
}
示例5: Main
public static void Main(String []argv)
{
IPAddress ip = IPAddress.Loopback;
Int32 port=1800;
if(argv.Length>0)
port = Int32.Parse(argv[0]);
IPEndPoint ep = new IPEndPoint(ip,port);
Socket ss = new Socket(AddressFamily.InterNetwork ,
SocketType.Stream , ProtocolType.Tcp);
try
{
ss.Bind(ep);
}
catch(SocketException err)
{
Console.WriteLine("** Error : socket already in use :"+err);
Console.WriteLine(" Please wait a few secs & try");
}
ss.Listen(-1);
Console.WriteLine("Server started and running on port {0}.....",port);
Console.WriteLine("Access URL http://localhost:{0}",port);
Socket client = null;
while(true)
{
client=ss.Accept();
SocketMessenger sm=new SocketMessenger(client);
sm.Start();
}
Console.WriteLine(client.LocalEndPoint.ToString()+" CONNECTED ");
ss.Close();
}
示例6: StartListening
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
byte[] msg = null;
// Echo the data back to the client.
while (true)
{
data = Guid.NewGuid().ToString();
msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
Console.WriteLine("Text sent : {0} {1}", data, DateTime.Now.ToString());
System.Threading.Thread.Sleep(1000);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.ReadLine();
}
示例7: AcceptTcpClients
private static void AcceptTcpClients(Socket serverSocket)
{
while (true) {
// accept client
Socket clientSocket = serverSocket.Accept();
_logger.Log(string.Format ("accepted client from {0}", Utils.IPAddressToString(clientSocket.RemoteEndPoint)));
Concurrency.StartThread(() => HandleTcpClient(clientSocket), "server handle client", _logger);
}
}
示例8: StartAcceptingConnections
private void StartAcceptingConnections(Socket socket)
{
var task = new Task(() =>
{
while (!socket.IsDisposed)
{
var connection = socket.Accept();
if (connection != null)
StartReceivingMessages(connection, new byte[socket.ReceiveBufferSize]);
}
}, TaskCreationOptions.LongRunning);
task.Start();
}
示例9: StartListeningInternal
private void StartListeningInternal()
{
byte[] bytes = new Byte[MessageSize];
try
{
var localEndPoint = new IPEndPoint(IpHelper.Ip, DefaultPort);
_listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listener.Bind(localEndPoint);
_listener.Listen(MaxConnections);
while (!_aborted)
{
Socket handler = _listener.Accept();
var data = "";
while (!_aborted)
{
try
{
bytes = new byte[Transport.PacketSize];
var bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf(Transport.EndFlag) > -1)
break;
}
catch (Exception ex)
{
Debug.Log(ex);
}
}
// Echo the data back to the client.
var result = _serverProtocol.ProcessRequest(data);
if (result!=null)
handler.Send(Encoding.ASCII.GetBytes(result+Transport.EndFlag));
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
_listener.Shutdown(SocketShutdown.Both);
_listener.Close();
}
catch (Exception e)
{
Debug.Log(e);
}
}
示例10: ticksrv_srv
static void ticksrv_srv()
{
Socket csock = null;
int sync_err = 0;
ticksrv_state = true;
ticksrv_sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ticksrv_sck.Bind(new IPEndPoint(IPAddress.Parse(ticksrv_Ip), ticksrv_Port));
ticksrv_sck.Listen(5);
ticksrv_sck.ReceiveTimeout = 12000;
while (true)
{
csock = null;
try
{
Console.WriteLine("Wait tick client in ");
csock = ticksrv_sck.Accept(); // 等待Client 端連線
}
catch
{
Console.WriteLine("Wait tick client , error ");
}
if (csock != null)
{
ticksrv_state = true;
sync_err = 0;
Console.WriteLine("quote tick srv con in");
Thread.Sleep(1);
}
while (ticksrv_state == true)
{
while (Quote.msg.ticksrv_kgidata_flash == false)
Thread.Sleep(1);
byte[] tick_data;
try
{
tick_data = Encoding.ASCII.GetBytes("tick_data;" + Quote.msg.Get_tick_P().ToString() + ";" + Quote.msg.Get_tick_v().ToString() + ";" + Quote.msg.Get_tick_t().ToString() + ";e");
csock.Send(tick_data);
}
catch
{
sync_err++;
}
if (sync_err > 1)
{
ticksrv_state = false;
break;
}
}
}
}
示例11: SynchronousSocketListener
public SynchronousSocketListener(int port)
{
// Data buffer for incoming data.
bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
//while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
handler = listener.Accept();
/*
handler.Shutdown(SocketShutdown.Both);
handler.Close();
*/
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
/*
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
*/
}
示例12: Main
public static int Main(String[] args)
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1 << 20];
IPEndPoint localEndPoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 5001);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
Console.WriteLine("Connected");
try
{
while (true)
{
handler.Receive(bytes);
}
}
catch (Exception) { }
Console.WriteLine("Connection terminated");
try { handler.Shutdown(SocketShutdown.Both); }
catch (Exception) { }
try { handler.Close(); }
catch (Exception) { }
try { handler.Dispose(); }
catch (Exception) { }
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return 0;
}
示例13: Main
public static void Main(String[] args)
{
KDTree = new KdTree<float,int> (2, new FloatMath ());
idMap = new Dictionary<int, AskObject> ();
maxObjectId = 0;
Socket listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind (new IPEndPoint (IPAddress.Any, 1234));
listener.Listen (100);
while (true) {
Socket handler = listener.Accept ();
ASKServer askServer = new ASKServer (handler);
Thread mythread = new Thread (askServer.run);
mythread.Start ();
}
}
示例14: AcceptIncoming
static TcpClient AcceptIncoming(Socket listeningSocket)
{
try
{
var tcpSocket = listeningSocket.Accept();
tcpSocket.Blocking = true;
Debug.Log("accepted incoming socket");
return new TcpClient {Client = tcpSocket};
}
catch (SocketException ex)
{
if (ex.ErrorCode == (int)SocketError.WouldBlock)
return null;
Debug.Log("SocketException in AcceptIncoming: " + ex);
throw (ex);
}
}
示例15: StartCore
private Socket _listenSocket; // прослушивающий сокет
protected void StartCore()
{
// создаем прослушивающий сокет
//Log.Info ("sdfsdfds");
Console.WriteLine ("sdddddd");
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.AcceptConnection, true);
// _listenSocket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
_listenSocket.Bind(_serverEndPoint);
_listenSocket.Listen(10);
Log.Info ("dffffff");
Socket s = _listenSocket.Accept ();
s.Send (System.Text.Encoding.ASCII.GetBytes("sendMessage"));
//_cancellationSource = new CancellationTokenSource();
// начать цикл приема входящих подключений
//StartAccepting();
}