本文整理汇总了C#中System.Net.Sockets.Socket.Listen方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Listen方法的具体用法?C# Socket.Listen怎么用?C# Socket.Listen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.Listen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: server_socket
public server_socket( Object name, int port )
: base()
{
try {
/* _server_socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); */
/* _server_socket.Bind( new IPEndPoint( 0, port ) ); */
IPEndPoint endpoint;
if( name != bigloo.foreign.BFALSE ) {
String server = bigloo.foreign.newstring( name );
IPHostEntry host = Dns.Resolve(server);
IPAddress address = host.AddressList[0];
endpoint = new IPEndPoint(address, port);
} else {
endpoint = new IPEndPoint( 0, port );
}
_server_socket = new Socket( endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp );
_server_socket.Bind( endpoint );
_server_socket.Listen( 10 );
}
catch (Exception e) {
socket_error( "make-server-socket",
"cannot create socket (" + e.Message + ")",
new bint( port ) );
}
}
示例2: connect
public bool connect(string strIP, int portNum, int readTimeOut)
{
IPAddress[] ipAddr = Dns.GetHostAddresses(strIP);
IPAddress ip = ipAddr[0];
IPEndPoint hostEP = new IPEndPoint(ip, portNum);
isConnected = true;
try
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化socket
s.Bind(hostEP);
s.Listen(0);
socket = s.Accept();
//尝试连接 客户端时
//socket=socket.Connect(hostEP);
}
catch (Exception se)
{
//MessageBox.Show("连接错误" + se.Message, "提示信息", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
Console.WriteLine("连接错误" + se.Message);
isConnected = false;
return false;
}
ns = new NetworkStream(socket);
if (readTimeOut < 0)
readTimeOut = 0;
ns.ReadTimeout = readTimeOut;
return isConnected;
}
示例3: send
//static void Main(string[] args, int a)
public void send()
{
String name = Id.name;
String a1 = "aantal schapen dood";
String a2 = link.a.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();
byte[] buffer = Encoding.Default.GetBytes(name);
byte[] buffer1 = Encoding.Default.GetBytes(a1 + name);
acc.Send(buffer, 0, buffer.Length, 0);
acc.Send(buffer1, 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();
}
示例4: ClientThread
public ClientThread()
{
listenPort = SRLibFun.StringConvertToInt32(SRConfig.Instance.GetAppString("Port"));
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketWatch.Bind(new IPEndPoint(GetIP(), listenPort));
socketWatch.Listen(10);
}
示例5: CreateTcp
public static ServerMock CreateTcp( int port, int bufferSize )
{
Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
socket.Bind( new IPEndPoint( IPAddress.Loopback, port ) );
socket.Listen( 16 );
return new ServerMock( socket, bufferSize );
}
示例6: StartServer
public static void StartServer()
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
serverSocket.Listen(10); //设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功\n", serverSocket.LocalEndPoint.ToString());
while (true)
{
allDone.Reset();
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//通过Clientsoket发送数据
//Thread myThread = new Thread(ListenClientConnect);
//myThread.Start();
Console.ReadLine();
}
示例7: Start
/// <summary>
/// Starts to listen
/// </summary>
/// <param name="config">The server config.</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
m_ListenSocket.Bind(this.Info.EndPoint);
m_ListenSocket.Listen(m_ListenBackLog);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
//
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
if (!m_ListenSocket.AcceptAsync(acceptEventArg))
ProcessAccept(acceptEventArg);
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
示例8: Main
static void Main(string[] args)
{
var listener = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
var ip = IPAddress.Parse("127.0.0.1");
var ep = new IPEndPoint(ip, 8000);
listener.Bind(ep);
listener.Listen(1);
for (; ; )
{
Console.WriteLine("接続待機中...");
Socket connection = listener.Accept();
// Accepted
Console.WriteLine("Accepted!!");
IPEndPoint remoteEP = (IPEndPoint)connection.RemoteEndPoint;
Console.WriteLine("Remote IP = {0}", remoteEP.Address);
Console.WriteLine("Remote Port = {0}", remoteEP.Port);
// Receive
byte[] receiveData = new byte[1000];
int size = connection.Receive(receiveData);
string receiveString = Encoding.UTF8.GetString(receiveData, 0, size);
Console.WriteLine("受信完了!");
Console.WriteLine("受信文字列 = {0}\n", receiveString);
}
}
示例9: Main
static List<Socket> klienciCzat = new List<Socket>(); //lista klientów - czyt. gniazd
static void Main(string[] args)
{
string adresIp = "192.168.1.163"; //podajemy adres ip naszezgo komputera na którym pracujemy trzeba go sprawdzic w cmd poprzez polecenie ipconfig następnie przepisać adres z ipv4 Address
//TODO: 1. Utworzenie punktu nadsłuchiwania - IPEndPoint
var punktNadsluchiwanie = new IPEndPoint(IPAddress.Parse(adresIp), 2000);
//TODO: 2. Utworzenie gniazda nadsłuchiwania - Socket
var gniazdo = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//TODO: 3. Przypisanie gniazda do adresu IP - Socket.Bind
gniazdo.Bind(punktNadsluchiwanie);
//TODO: 4. Rozpoczęcie nadsłuchiwania - Socket.Listen
gniazdo.Listen(10);
while (true)//TODO: 5. W pętli oczekiwanie na połączenia - Socket.Accept
{
var polaczenieZKlientem = gniazdo.Accept(); //oczekiwanie na połączenia
klienciCzat.Add(polaczenieZKlientem); //dodanie nowego klienta do listy
var danePolaczenie = string.Format("Port serwer: {0}; Klient: {1}:{2}",
((IPEndPoint)polaczenieZKlientem.LocalEndPoint).Port,
((IPEndPoint)polaczenieZKlientem.RemoteEndPoint).Address.ToString(),
((IPEndPoint)polaczenieZKlientem.RemoteEndPoint).Port);
Console.WriteLine(danePolaczenie);
var watek = new Thread(KlientCzat);
watek.IsBackground = true;
watek.Start(polaczenieZKlientem);
}
}
示例10: ConnectMaster
public void ConnectMaster()
{
if (c_Connected && c_Server)
return;
try
{
c_Server = true;
//Console.WriteLine("CM Close Slave");
CloseSlave();
c_Master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
c_Master.Bind(new IPEndPoint(IPAddress.Any, Data.MultiPort));
c_Master.Listen(4);
c_Master.BeginAccept(new AsyncCallback(OnClientConnect), null);
//Console.WriteLine("Started");
c_Connecting = false;
c_Connected = true;
}
catch (Exception /*e*/)// I HID e to stop warning message.
{
c_Server = false;
//Console.WriteLine(e.Message);
//Console.WriteLine(e.StackTrace);
}
}
示例11: ListenThreadFunc
void ListenThreadFunc()
{
Socket listenSocket = null;
try
{
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, _port);
listenSocket.Bind(ep);
LogThread.Log("ListenThread: Listening on port " + _port, LogThread.LogMessageType.Normal, true);
while (true)
{
listenSocket.Listen(10);
Socket conn = listenSocket.Accept();
if (conn != null && OnConnectionAccepted != null)
{
LogThread.Log("ListenThread: Connection Accepted", LogThread.LogMessageType.Debug);
OnConnectionAccepted(this, new SocketArg(conn));
}
}
}
catch (Exception ex)
{
LogThread.Log(ex.ToString(), LogThread.LogMessageType.Error, true);
listenSocket.Close();
_theThread = null;
}
}
示例12: Listen
internal void Listen(String ipAddress, Int32 portNo)
{
if (_isRunning == true)
throw new AegisException(ResultCode.AcceptorIsRunning, "Acceptor is already running.");
try
{
if (ipAddress.Length == 0)
_listenEndPoint = new IPEndPoint(IPAddress.Any, portNo);
else
_listenEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), portNo);
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.Bind(_listenEndPoint);
_listenSocket.Listen(100);
Logger.Write(LogType.Info, 1, "Listening on {0}, {1}", _listenEndPoint.Address, _listenEndPoint.Port);
_isRunning = true;
(new Thread(Run)).Start();
}
catch (Exception e)
{
throw new AegisException(ResultCode.NetworkError, e, e.Message);
}
}
示例13: Listen
/// <summary>
/// Listen to incoming data
/// </summary>
public void Listen()
{
//IPAddress ipAddr = IPAddress.Parse("10.241.129.147");
IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 5050);
Socket sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
sListener.Bind(ipEndPoint);
sListener.Listen(10);
while (true)
{
Console.WriteLine("Ожидаем соединение через порт {0}", ipEndPoint);
Socket handler = sListener.Accept();
RecieveDict(handler);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadLine();
}
}
示例14: Start_A_Server_On
// (1) Establish The Server
public string Start_A_Server_On(int Port)
{
try
{
IPAddress[] AddressAr = null;
String ServerHostName = "";
try
{
ServerHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(ServerHostName);
AddressAr = ipEntry.AddressList;
}
catch (Exception) { }
if (AddressAr == null || AddressAr.Length < 1)
{
return "Unable to get local address ... Error";
}
Listener_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Listener_Socket.Bind(new IPEndPoint(AddressAr[0], Port));
Listener_Socket.Listen(-1);
Listener_Socket.BeginAccept(new AsyncCallback(EndAccept), Listener_Socket);
return ("Listening On " + AddressAr[0].ToString() + ":" + Port + "... OK");
}
catch (Exception ex) { return ex.Message; }
}
示例15: Main
public static void Main()
{
using (Socket listeningSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp))
{
listeningSocket.Bind(new IPEndPoint(IPAddress.Any, port));
Debug.Print("Listening for a client...");
listeningSocket.Listen(1);
using (Socket communicationSocket = listeningSocket.Accept())
{
Debug.Print("Connected to client.");
using (SslStream sslStream = new SslStream(communicationSocket))
{
X509Certificate serverCert =
new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyServer));
X509Certificate rootCA =
new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
sslStream.AuthenticateAsServer(serverCert, // To authenticate the server
new X509Certificate[] { rootCA }, // CA certificates
SslVerification.CertificateRequired, // Verify client
SslProtocols.Default // Protocols that may be used
);
//wait infinitely to get a response
sslStream.ReadTimeout = -1;
byte[] inBuffer = new byte[1000];
int count = sslStream.Read(inBuffer, 0, inBuffer.Length);
string message = new string(Encoding.UTF8.GetChars(inBuffer));
Debug.Print("Received '" + message + "'.");
}
}
}
}