本文整理汇总了C#中System.Net.IPEndPoint类的典型用法代码示例。如果您正苦于以下问题:C# IPEndPoint类的具体用法?C# IPEndPoint怎么用?C# IPEndPoint使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
IPEndPoint类属于System.Net命名空间,在下文中一共展示了IPEndPoint类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: button1_Click
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
var ControllerPort = 40001;
var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var header = "@";
var command = "00C";
var checksum = "E3";
var end = "\r\n";
var data = header + command + checksum + end;
byte[] bytes = new byte[1024];
//Start Connect
_connectDone.Reset();
watch.Start();
_client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
//wait 2s
_connectDone.WaitOne(2000, false);
var text = (_client.Connected) ? "ok" : "ng";
richTextBox1.AppendText(text + "\r\n");
watch.Stop();
richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
}
示例2: InitConnect
internal void InitConnect(IPEndPoint serverEndPoint,
Action<IPEndPoint, Socket> onConnectionEstablished,
Action<IPEndPoint, SocketError> onConnectionFailed,
ITcpConnection connection,
TimeSpan connectionTimeout)
{
if (serverEndPoint == null)
throw new ArgumentNullException("serverEndPoint");
if (onConnectionEstablished == null)
throw new ArgumentNullException("onConnectionEstablished");
if (onConnectionFailed == null)
throw new ArgumentNullException("onConnectionFailed");
var socketArgs = _connectSocketArgsPool.Get();
var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socketArgs.RemoteEndPoint = serverEndPoint;
socketArgs.AcceptSocket = connectingSocket;
var callbacks = (CallbacksStateToken) socketArgs.UserToken;
callbacks.OnConnectionEstablished = onConnectionEstablished;
callbacks.OnConnectionFailed = onConnectionFailed;
callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout));
AddToConnecting(callbacks.PendingConnection);
try
{
var firedAsync = connectingSocket.ConnectAsync(socketArgs);
if (!firedAsync)
ProcessConnect(socketArgs);
}
catch (ObjectDisposedException)
{
HandleBadConnect(socketArgs);
}
}
示例3: Main
static void Main(string[] args)
{
var m_Config = new ServerConfig
{
Port = 911,
Ip = "Any",
MaxConnectionNumber = 1000,
Mode = SocketMode.Tcp,
Name = "CustomProtocolServer"
};
var m_Server = new CustomProtocolServer();
m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
m_Server.Start();
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);
using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(serverAddress);
var socketStream = new NetworkStream(socket);
var reader = new StreamReader(socketStream, Encoding.ASCII, false);
string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty);
Random rd = new Random();
var watch = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
int startPos = rd.Next(0, charSource.Length - 2);
int endPos = rd.Next(startPos + 1, charSource.Length - 1);
var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);
byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
socketStream.Write(requestNameData, 0, requestNameData.Length);
var data = Encoding.ASCII.GetBytes(currentMessage);
socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
socketStream.Write(data, 0, data.Length);
socketStream.Flush();
// Console.WriteLine("Sent: " + currentMessage);
var line = reader.ReadLine();
//Console.WriteLine("Received: " + line);
//Assert.AreEqual(currentMessage, line);
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
Console.ReadLine();
}
示例4: Main
static void Main(string[] args)
{
byte[] receiveBytes = new byte[1024];
int port =8080;//服务器端口
string host = "10.3.0.1"; //服务器ip
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Console.WriteLine("Starting Creating Socket Object");
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);//创建一个Socket
sender.Connect(ipe);//连接到服务器
string sendingMessage = "Hello World!";
byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
sender.Send(forwardingMessage);
int totalBytesReceived = sender.Receive(receiveBytes);
Console.WriteLine("Message provided from server: {0}",
Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived));
//byte[] bs = Encoding.ASCII.GetBytes(sendStr);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
}
示例5: Main
public static void Main()
{
using (Socket clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp))
{
// Addressing
IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress);
IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port);
// Connecting
Debug.Print("Connecting to server " + serverEndPoint + ".");
clientSocket.Connect(serverEndPoint);
Debug.Print("Connected to server.");
using (SslStream sslStream = new SslStream(clientSocket))
{
X509Certificate rootCA =
new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
X509Certificate clientCert =
new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
sslStream.AuthenticateAsClient("MyServerName", // Hostname needs to match CN of server cert
clientCert, // Authenticate client
new X509Certificate[] { rootCA }, // CA certs for verification
SslVerification.CertificateRequired, // Verify server
SslProtocols.Default // Protocols that may be required
);
// Sending
byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!");
sslStream.Write(messageBytes, 0, messageBytes.Length);
}
}// the socket will be closed here
}
示例6: 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 { }
}
}
示例7: Get
/// <summary>
/// Gets a list of variable binds.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <returns></returns>
public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
{
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (version == VersionCode.V3)
{
throw new NotSupportedException("SNMP v3 is not supported");
}
var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
var response = message.GetResponse(timeout, endpoint);
var pdu = response.Pdu();
if (pdu.ErrorStatus.ToInt32() != 0)
{
throw ErrorException.Create(
"error in response",
endpoint.Address,
response);
}
return pdu.Variables;
}
示例8: Send
internal void Send(byte[] data, IPEndPoint receiver)
{
lock (UDPSocket)
{
UDPSocket.SendTo(data, receiver);
}
}
示例9: CreateConnectingTcpConnection
public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId,
IPEndPoint remoteEndPoint,
TcpClientConnector connector,
TimeSpan connectionTimeout,
Action<ITcpConnection> onConnectionEstablished,
Action<ITcpConnection, SocketError> onConnectionFailed,
bool verbose)
{
var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose);
// ReSharper disable ImplicitlyCapturedClosure
connector.InitConnect(remoteEndPoint,
(_, socket) =>
{
if (connection.InitSocket(socket))
{
if (onConnectionEstablished != null)
onConnectionEstablished(connection);
connection.StartReceive();
connection.TrySend();
}
},
(_, socketError) =>
{
if (onConnectionFailed != null)
onConnectionFailed(connection, socketError);
}, connection, connectionTimeout);
// ReSharper restore ImplicitlyCapturedClosure
return connection;
}
示例10: serverLoop
protected void serverLoop()
{
Trace.WriteLine("Waiting for UDP messages.");
listener = new UdpClient(UDP_PORT);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_PORT);
byte[] receive_byte_array;
bool running = true;
while (running)
{
try
{
receive_byte_array = listener.Receive(ref groupEP);
if (receive_byte_array.Length != 2)
{
Trace.WriteLine("Invalid UDP message received. Ignored message!");
continue;
}
Trace.WriteLine("Upp fan speed message received.");
int fan = receive_byte_array[0];
byte speed = receive_byte_array[1];
fanControlDataObject.setPinSpeed(fan, speed, true);
}
catch
{
running = false;
}
}
}
示例11: 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 ) );
}
}
示例12: Test_Default
public void Test_Default()
{
var config = new ClientConfiguration();
Assert.AreEqual(1, config.BucketConfigs.Count);
var bucketConfig = config.BucketConfigs.First().Value;
IPAddress ipAddress;
IPAddress.TryParse("127.0.0.1", out ipAddress);
var endPoint = new IPEndPoint(ipAddress, bucketConfig.Port);
Assert.AreEqual(endPoint, bucketConfig.GetEndPoint());
Assert.IsEmpty(bucketConfig.Password);
Assert.IsEmpty(bucketConfig.Username);
Assert.AreEqual(11210, bucketConfig.Port);
Assert.AreEqual("default", bucketConfig.BucketName);
Assert.AreEqual(2, bucketConfig.PoolConfiguration.MaxSize);
Assert.AreEqual(1, bucketConfig.PoolConfiguration.MinSize);
Assert.AreEqual(2500, bucketConfig.PoolConfiguration.RecieveTimeout);
Assert.AreEqual(2500, bucketConfig.PoolConfiguration.OperationTimeout);
Assert.AreEqual(10000, bucketConfig.PoolConfiguration.ShutdownTimeout);
Assert.AreEqual(2500, bucketConfig.DefaultOperationLifespan);
Assert.AreEqual(75000, config.ViewRequestTimeout);
}
示例13: ConnectIPAddressAny
public void ConnectIPAddressAny ()
{
IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0);
/* UDP sockets use Any to disconnect
try {
using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
s.Connect (ep);
s.Close ();
}
Assert.Fail ("#1");
} catch (SocketException ex) {
Assert.AreEqual (10049, ex.ErrorCode, "#2");
}
*/
try {
using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
s.Connect (ep);
s.Close ();
}
Assert.Fail ("#3");
} catch (SocketException ex) {
Assert.AreEqual (10049, ex.ErrorCode, "#4");
}
}
示例14: IPEndPoint
/*
// TODO: Асинхронная отправка! Или не нужно?
/// <summary>
/// Отправить единичное сообщение на единичный хост
/// </summary>
/// <param name="text">Текст сообщения</param>
// internal static void SendMessage(string RemoteHost, string text)
{
TcpClient client = null;
NetworkStream networkStream = null;
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
// TODO : заменить 127.0.0.1 на что-то более верное
// TODO: добавить динамическое выделение портов (из пула свободных портов)
// получатель сообщения при
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
// TODO :забить номера портов в настройки
client = new TcpClient(localEndPoint);
client.Connect(remoteEndPoint);
networkStream = client.GetStream();
byte[] sendBytes = Encoding.UTF8.GetBytes(text);
networkStream.Write(sendBytes, 0, sendBytes.Length);
byte[] bytes = new byte[client.ReceiveBufferSize];
networkStream.Read(bytes, 0, client.ReceiveBufferSize);
string returnData = Encoding.UTF8.GetString(bytes);
//MessageBox.Show(returnData);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (networkStream != null) networkStream.Close();
if (client!=null) client.Close();
}
}
*/
// реализаця с UDP
internal static void SendMessage(string RemoteHost, string text)
{
UdpClient client = null;
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
// получатель сообщения при
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
// TODO :забить номера портов в настройки
client = new UdpClient(localEndPoint);
byte[] sendBytes = Encoding.ASCII.GetBytes(text);
networkStream.Write(sendBytes, 0, sendBytes.Length);
byte[] bytes = new byte[client.ReceiveBufferSize];
networkStream.Read(bytes, 0, client.ReceiveBufferSize);
string returnData = Encoding.UTF8.GetString(bytes);
//MessageBox.Show(returnData);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (networkStream != null) networkStream.Close();
if (client != null) client.Close();
}
}
示例15: ConnectAsync
public Task<Socket> ConnectAsync(IPEndPoint remoteEndPoint)
{
_connectTcs = new TaskCompletionSource<Socket>();
var task = _connectTcs.Task;
Connect(remoteEndPoint);
return task;
}