本文整理汇总了C#中System.Net.Sockets.Socket.Bind方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Bind方法的具体用法?C# Socket.Bind怎么用?C# Socket.Bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.Bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WebServer
public WebServer()
{
greenThread = new Thread(green.LightControl);
greenThread.Start();
amberThread = new Thread(amber.LightControl);
amberThread.Start();
redThread = new Thread(red.LightControl);
redThread.Start();
//Initialize Socket class
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Request and bind to an IP from DHCP server
socket.Bind(new IPEndPoint(IPAddress.Any, 80));
string address =
Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
//Debug print our IP address
while (address == "192.168.5.100")
{
address =
Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
Thread.Sleep(2000);
}
Debug.Print(address);
//Start listen for web requests
socket.Listen(10);
ListenForRequest();
}
示例2: Server
private static void Server()
{
list = new List<IPAddress>();
const ushort data_size = 0x400; // = 1024
byte[] data;
while (ServerRun)
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort);
try
{
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
data = new byte[data_size];
if (!ServerRun) break;
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));
data = new byte[data_size];
if (!ServerRun) break;
recv = sock.ReceiveFrom(data, ref ep);
stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));
sock.Close();
}
catch { }
}
}
示例3: 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 ) );
}
}
示例4: RecieveCallback
protected override void RecieveCallback(IAsyncResult Result)
{
DatagramState Dstate = (DatagramState)Result.AsyncState;
int bytes = 0;
Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
S.Bind(new IPEndPoint(IPAddress.Any, 0));
Socket past = Dstate.ClientSocket;
Dstate.ClientSocket = S;
try
{
bytes = past.EndReceiveFrom(Result, ref Dstate.EndPoint);
}
catch (Exception e)
{
Next.Set();
Send("Respect the buffer size which is " + DatagramState.BufferSize.ToString(), Dstate);
return;
}
if (bytes>0)
{
string content = "";
Dstate.MsgBuilder.Append(Encoding.ASCII.GetString(Dstate.Buffer, 0, bytes));
content = Dstate.MsgBuilder.ToString();
Next.Set();
try
{
string r = Calculate(content).ToString();
Send(r, Dstate);
}
catch (Exception e)
{
Send(e.Message, Dstate);
}
}
}
示例5: Http2SocketServer
public Http2SocketServer(Func<IDictionary<string, object>, Task> next, IDictionary<string, object> properties)
{
_next = next;
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp); // Dual mode
IList<IDictionary<string, object>> addresses =
(IList<IDictionary<string, object>>)properties[OwinConstants.CommonKeys.Addresses];
IDictionary<string, object> address = addresses.First();
_enableSsl = !string.Equals((address.Get<string>("scheme") ?? "http"), "http", StringComparison.OrdinalIgnoreCase);
_port = Int32.Parse(address.Get<string>("port") ?? (_enableSsl ? "443" : "80"), CultureInfo.InvariantCulture);
string host = address.Get<string>("host");
if (string.IsNullOrWhiteSpace(host) || !host.Equals("*") || !host.Equals("+"))
{
_socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port));
}
else
{
_socket.Bind(new IPEndPoint(Dns.GetHostAddresses(host)[0], _port));
}
Listen();
}
示例6: DccListener
internal DccListener(DccClient client, TimeSpan timeout, int port)
{
m_client = client;
m_timeout = timeout;
m_Port = port;
m_closed = false;
m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
try
{
m_sock.Bind(new IPEndPoint(Util.ExternalAddress, m_Port));
}
catch
{
m_sock.Bind(new IPEndPoint(Util.LocalHostAddress, m_Port));
}
m_sock.Listen(1);
m_sock.BeginAccept(new AsyncCallback(OnAccept), null);
}
catch (Exception ex)
{
m_client.Dcc.ListenerFailedNotify(this, ex);
}
m_timeoutTimer = new Timer(m_timeout.TotalMilliseconds);
m_timeoutTimer.Elapsed += OnTimeout;
m_timeoutTimer.Start();
}
示例7: StartListening
public bool StartListening(AddressFamily family, int port, Func<IPEndPoint, INetworkConnection> getConMethod)
{
try
{
GetConnnection = getConMethod;
if (Socket == null)
{
Socket = new System.Net.Sockets.Socket(family, SocketType.Dgram, ProtocolType.Udp);
Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Socket.ExclusiveAddressUse = false;
if (family == AddressFamily.InterNetworkV6)
{
Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0); // set IPV6Only to false. enables dual mode socket - V4+v6
Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
}
else
{
Socket.Bind(new IPEndPoint(IPAddress.Any, port));
}
}
Port = ((IPEndPoint)Socket.LocalEndPoint).Port;
m_ListenArgs = new byte[1024];
m_ListenerThread = new Thread(new ThreadStart(DoListen));
m_ListenerThread.IsBackground = true;
m_ListenerThread.Name = "UDPListenerSimplex Read Thread";
m_State = new SockState(null, 1024, null);
if (family == AddressFamily.InterNetworkV6)
{
m_EndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
}
else
{
m_EndPoint = new IPEndPoint(IPAddress.Any, 0);
}
m_ListenerThread.Start();
}
catch (Exception e)
{
Log.LogMsg("UDPListenerSimplex - error start listen: " + e.Message);
return false;
}
Listening = true;
Log.LogMsg("UDPListenerSimplex - Listening for UDP traffic on port " + port.ToString());
return true;
}
示例8: OpenChannel
public void OpenChannel()
{
var logger = _loggerFactory.CreateLogger($"OpenChannel");
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, _port));
_listenSocket.Listen(10);
logger.LogInformation($"Process ID {Process.GetCurrentProcess().Id}");
logger.LogInformation($"Listening on port {_port}");
while (true)
{
var acceptSocket = _listenSocket.Accept();
logger.LogInformation($"Client accepted {acceptSocket.LocalEndPoint}");
var connection = new ConnectionContext(acceptSocket,
_hostName,
_protocolManager,
_workspaceContext,
_projects,
_loggerFactory);
connection.QueueStart();
}
}
示例9: connectAsync
/**
* Asynchronously connects to the localhost server on the cached port number.
* Sets up a TCP socket attempting to contact localhost:outPort, and a
* corresponding UDP server, bound to the inPort.
*
* UNDONE: Think about establishing TCP communication to request what port to set up,
* in case ports can't be directly forwarded, etc. and Unity doesn't know.
*
* Returns True if the connection was successful, false otherwise.
*/
public bool connectAsync(){
try {
/* Create TCP socket for authenticated communication */
endpt = new IPEndPoint(IPAddress.Parse(host), outPort);
clientAuth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientAuth.BeginConnect(endpt, new AsyncCallback(connectCallback), clientAuth);
/* Set up nondurable UDP server for receiving actions*/
server = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Blocking = false;
/*Set up nondurable UDP client to send gamestate */
IPEndPoint RemoteEndPoint= new IPEndPoint(IPAddress.Parse(host), outPort);
clientGameState = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
/* Bind to UDP host port */
IPEndPoint inpt = new IPEndPoint(IPAddress.Parse(host), inPort);
server.Bind (inpt);
return true;
} catch (Exception e){
Debug.Log (e);
return false;
}
}
示例10: 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 );
}
示例11: ManagmentService
static ManagmentService()
{
ClientList = new List<IncomingClient>();
AppSettingsReader _settingsReader = new AppSettingsReader();
string value = _settingsReader.GetValue("ServerRunAtIP", type: typeof(string)) as string;
if (!IPAddress.TryParse(value, out ServerIP))
throw new Exception(message: "Appseting ServerRunAtIP Error");
value = _settingsReader.GetValue("ServerRunAtPort", type: typeof(string)) as string;
if (!int.TryParse(value, out ServerPort))
throw new Exception(message: "Appseting ServerRunAtPort Error");
value = _settingsReader.GetValue("MaxPoolClient", type: typeof(string)) as string;
if (!int.TryParse(value, out MaxClient))
throw new Exception(message: "Appseting MaxPoolClient Error");
ServerEndPoint = new IPEndPoint(ServerIP, ServerPort);
ServerLisenerSocket = new Socket(addressFamily: AddressFamily.InterNetwork, socketType: SocketType.Stream, protocolType: ProtocolType.Tcp);
ServerLisenerSocket.Bind(ServerEndPoint);
}
示例12: Main
static void Main(string[] args)
{
//1.创建socket
Socket tpcServer = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
//2.绑定ip跟端口号 192.168.1.105
IPAddress ipaddress = new IPAddress(new byte[]{192,168,1,105});
EndPoint point = new IPEndPoint(ipaddress,7788);//ipendpoint 是对ip + 端口做了一层封装的类
tpcServer.Bind(point); //向操作系统申请一个可用的ip跟端口号 用来做通信
//3.开始监听 (等待客户端连接)
tpcServer.Listen(100); //参数是最大连接数
Console.WriteLine("开始监听");
Socket clientSocket = tpcServer.Accept(); //暂停当前的线程,直到有一个客户端连接过来,之后进行下面的代码
//使用返回的socket跟客户端做通信
Console.WriteLine("客户端连接过来了");
string message = "hello 欢迎你 ";
byte[] data = Encoding.UTF8.GetBytes(message);//对字符串做编码,得到一个字符串的字节数组
clientSocket.Send(data);
Console.WriteLine("向客户端发送数据");
byte[] data2 = new byte[1024]; //创建一个字节数组用来做容器,去承接客户端发送过来的数据
int length = clientSocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2, 0, length);// 把字节数转化成一个字符串
Console.WriteLine("接收到了一个从客户端发送过来的消息");
Console.WriteLine(message2);
Console.ReadKey();
}
示例13: Server
/// <summary>
/// Creates an NeonMika.Webserver instance
/// </summary>
/// <param name="portNumber">The port to listen for incoming requests</param>
public Server(int portNumber = 80, bool DhcpEnable = true, string ipAddress = "", string subnetMask = "", string gatewayAddress = "")
{
var interf = NetworkInterface.GetAllNetworkInterfaces()[0];
if (DhcpEnable)
{
//Dynamic IP
interf.EnableDhcp();
//interf.RenewDhcpLease( );
}
else
{
//Static IP
interf.EnableStaticIP(ipAddress, subnetMask, gatewayAddress);
}
Debug.Print("Webserver is running on " + interf.IPAddress + " /// DHCP: " + interf.IsDhcpEnabled);
this._PortNumber = portNumber;
ResponseListInitialize();
_ListeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ListeningSocket.Bind(new IPEndPoint(IPAddress.Any, portNumber));
_ListeningSocket.Listen(4);
}
示例14: 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();
}
示例15: 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;
}
}