本文整理汇总了C#中System.Net.Sockets.Socket.SetSocketOption方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.SetSocketOption方法的具体用法?C# Socket.SetSocketOption怎么用?C# Socket.SetSocketOption使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.SetSocketOption方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LANGameManager
public LANGameManager(Game game, String name, String description, int maxDataSize = 1024,
int ttl = 1, float introductionFrequency = 2, IPAddress multicastIpAddress = null)
: base(game)
{
this.name = name;
this.description = description;
this.introFreq = introductionFrequency;
this.incomingDataBuffer = new Byte[maxDataSize];
// register us
game.Services.AddService(typeof(LANGameManager), this);
game.Components.Add(this);
Registry.Register(this);
// set up our broadcast communication
multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
if (multicastIpAddress != null)
{
multicastIpAddr = multicastIpAddress;
}
multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
new MulticastOption(multicastIpAddr));
multicastSocket.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, ttl);
multicastEndPoint = new IPEndPoint(multicastIpAddr, 4567);
multicastSocket.Connect(multicastEndPoint);
}
示例2: Listen
public virtual void Listen(int port)
{
// Check if the server has been disposed.
if (_disposed) throw new ObjectDisposedException(this.GetType().Name, "Server has been disposed.");
// Check if the server is already listening.
if (IsListening) throw new InvalidOperationException("Server is already listening.");
// Create new TCP socket and set socket options.
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try {
// This is failing on Linux; dunno why.
Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
} catch (SocketException e) {
Logger.DebugException(e, "Listen");
}
Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
// Bind.
Listener.Bind(new IPEndPoint(IPAddress.Any, port));
this.Port = port;
// Start listening for incoming connections.
Listener.Listen(10);
IsListening = true;
// Begin accepting any incoming connections asynchronously.
Listener.BeginAccept(AcceptCallback, null);
}
示例3: Initialize
private void Initialize(IPEndPoint endpoint, Action<TcpStreamChannel> onClientAccepted)
{
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
if (onClientAccepted == null)
{
throw new ArgumentNullException("onClientConnected");
}
_onClientAcceptedAction = onClientAccepted;
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
_listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
_listenSocket.Bind(endpoint);
_listenSocket.Listen(10);
_acceptEventArg = new SocketAsyncEventArgs();
_acceptEventArg.Completed += OnAcceptNewClient;
if (!_listenSocket.AcceptAsync(_acceptEventArg))
{
OnAcceptNewClient(null, _acceptEventArg);
}
}
示例4: Start
///<summary>
/// Starts listening to network notifications
///</summary>
public void Start()
{
if (socket != null)
{
if (!IsStop) return;
StartListening();
IsStop = false;
return;
}
IsStop = false;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters.Where(card => card.OperationalStatus == OperationalStatus.Up))
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (var ipaddress in properties.UnicastAddresses.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork))
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, (object)new MulticastOption(IPAddress.Parse("224.0.0.1"), ipaddress.Address));
}
}
socket.Bind(new IPEndPoint(IPAddress.Any, 12391));
StartListening();
}
示例5: Connect
public void Connect()
{
var hostEntry = Dns.GetHostEntry(config.Url);
var address = hostEntry.AddressList[0];
var endpoint = new IPEndPoint(IPAddress.Loopback, config.Port);
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(endpoint);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, config.BufferSize);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, config.BufferSize);
stream = new NetworkStream(client, true);
serverProperties = ReadServerProperties(client);
var reader = serverProperties.CreateReader();
var writer = serverProperties.CreateWriter();
if (serverProperties.AuthenticateRequired)
TryLogin(writer, config.Username, config.Password);
sender = new VanillaDataStorageSender(this, name, writer, snapshotManager, config.Serializer, mapper);
receiver = new VanillaDataStorageReceiver(this, name, reader, config.Serializer, mapper);
sender.Start();
receiver.Start();
}
示例6: initializeConnection
public bool initializeConnection()
{
try
{
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
m_socket.SendTimeout = 5000;
m_socket.ReceiveTimeout = 5000;
m_frm.Print("Connecting to " + ECCServerIP + " at port " + ECCServerPort + " ...");
m_socket.Connect(ECCServerIP, Convert.ToInt32(ECCServerPort));
}
catch (Exception ex)
{
m_frm.Print("Error!Failed to connect to ECC server!" + ex.Message);
return false;
}
if (!Authenticate())
return false;
return true;
}
示例7: CSocket
public CSocket(IPEndPoint _endPoint, ScoketPool _pool, SocketPoolProfile config)
{
socketConfig = config;
endpoint = _endPoint;
pool = _pool;
Socket _socket = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000/*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle);
_socket.Connect(_endPoint);
socket = _socket;
this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize);
Thread th = new Thread(delegate() {
while (true)
{
try
{
Receive();
}
catch (Exception ex)
{
logger.Notice(ex.Message);
}
}
});
th.Start();
}
示例8: PooledSocket
public PooledSocket(SocketPool socketPool, IPEndPoint endPoint, int sendReceiveTimeout, int connectTimeout)
{
this.socketPool = socketPool;
Created = DateTime.Now;
//Set up the socket.
socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
socket.ReceiveTimeout = sendReceiveTimeout;
socket.SendTimeout = sendReceiveTimeout;
//Do not use Nagle's Algorithm
socket.NoDelay = true;
//Establish connection asynchronously to enable connect timeout.
IAsyncResult result = socket.BeginConnect(endPoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(connectTimeout, false);
if (!success) {
try { socket.Close(); } catch { }
throw new SocketException();
}
socket.EndConnect(result);
//Wraps two layers of streams around the socket for communication.
stream = new BufferedStream(new NetworkStream(socket, false));
}
示例9: Start
/// <summary>
/// 启动监听
/// </summary>
/// <param name="config">服务器配置</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
m_ListenSocket = new System.Net.Sockets.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);
//初始化套接字操作
SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
m_AcceptSAE = acceptEventArg;
//定义一个连接完成事件
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
if (!m_ListenSocket.AcceptAsync(acceptEventArg))
{
ProcessAccept(acceptEventArg);
}
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
示例10: createClient
public void createClient(int coreManagerId)
{
try
{
byte[] commandBuffer = createConnection(coreManagerId);
if (commandBuffer == null) return;
Command resultCommand = AbstractCommand.deSerialize(commandBuilder, commandBuffer, 0, commandBuffer.Length);
CommandStatus status = resultCommand.getStatus();
if (!CommandStatus.success.Equals(status))
{
throw new PlanckDBException(status, "Fail to create connection due to " + status.getMessage());
}
multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse(dbProperties.getMulticastIp());
multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 2);
IPEndPoint ipep = new IPEndPoint(ip, 4567);
multicastSocket.Connect(ipep);
//multicastSocket.setInterface(InetAddress.getByName(dbProperties.getNetworkInterface()));
active = true;
Thread thread = new Thread(new ThreadStart(run));
thread.Start();
Thread.Sleep(1000);
}catch (PlanckDBException e){
multicastConnectionHolder.handleMulticastConnectionFailure(this);
throw e;
}
catch (Exception e)
{
multicastConnectionHolder.handleMulticastConnectionFailure(this);
throw new PlanckDBException(CommandStatus.unsupported, "TCP connection failure due to IOException : " + e.Message);
}
}
示例11: 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;
}
}
示例12: RegisterSession
protected ISocketSession RegisterSession(Socket client, ISocketSession session)
{
if (m_SendTimeOut > 0)
client.SendTimeout = m_SendTimeOut;
if (m_ReceiveBufferSize > 0)
client.ReceiveBufferSize = m_ReceiveBufferSize;
if (m_SendBufferSize > 0)
client.SendBufferSize = m_SendBufferSize;
if(!Platform.SupportSocketIOControlByCodeEnum)
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
else
client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, null);
client.NoDelay = true;
client.UseOnlyOverlappedIO = true;
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
IAppSession appSession = this.AppServer.CreateAppSession(session);
if (appSession == null)
return null;
return session;
}
示例13: GDISendingChannel
public GDISendingChannel(GDIDeviceContext dc)
{
fFormatter = new BinaryFormatter();
fMemoryStream = new MemoryStream(2048);
fDeviceContext = dc;
// Create the client
fGDISpeaker = new UdpClient();
// Create the broadcast socket
IPAddress ip = IPAddress.Parse(GDIPortal.Multicast_Pixtour_Group);
fBroadcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
fBroadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
fBroadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(GDIPortal.Multicast_Pixtour_Group), GDIPortal.Multicast_Pixtour_Port);
fBroadcastSocket.Connect(ipep);
// Setup the speaker
fGraphPort = new GCDelegate(fDeviceContext.Resolution);
fGraphPort.CommandPacked += new GCDelegate.DrawCommandProc(CommandPacked);
// Setup the antennae to listen for commands
fReceiver = new GDIReceivingChannel(GDIPortal.Multicast_Pixtour_Group, GDIPortal.Multicast_Pixtour_Port, fDeviceContext);
}
示例14: Start
public void Start()
{
lock(runLock)
{
if(isRunning)
{
return;
}
var ipEndPoint = new IPEndPoint(IPAddress.Any, Settings.Port);
var listenEndPoint = (EndPoint) ipEndPoint;
multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
multicastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, Settings.TimeToLive);
multicastSocket.Bind(ipEndPoint);
var multicastOption = new MulticastOption(Settings.MulticastGroupAddress, IPAddress.Any);
multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);
var stateObject = new StateObject { Socket = multicastSocket };
multicastSocket.BeginReceiveFrom(stateObject.Buffer, 0, stateObject.Buffer.Length, SocketFlags.None, ref listenEndPoint, OnReceiveSocketData, stateObject);
isRunning = true;
}
}
示例15: SendWWTRemoteCommand
public static void SendWWTRemoteCommand(string targetIP, string command, string param)
{
Socket sockA = null;
IPAddress target = null;
sockA = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
if(targetIP == "255.255.255.255")
{
sockA.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
target = IPAddress.Broadcast;
}
else
{
target = IPAddress.Parse(targetIP);
}
IPEndPoint bindEPA = new IPEndPoint(IPAddress.Parse(NetControl.GetThisHostIP()), 8099);
sockA.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
sockA.Bind(bindEPA);
EndPoint destinationEPA = (EndPoint)new IPEndPoint(target, 8089);
string output = "WWTCONTROL2" + "," + Earth3d.MainWindow.Config.ClusterID + "," + command + "," + param;
Byte[] header = Encoding.ASCII.GetBytes(output);
sockA.SendTo(header, destinationEPA);
sockA.Close();
}