当前位置: 首页>>代码示例>>C#>>正文


C# Socket类代码示例

本文整理汇总了C#中Socket的典型用法代码示例。如果您正苦于以下问题:C# Socket类的具体用法?C# Socket怎么用?C# Socket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Socket类属于命名空间,在下文中一共展示了Socket类的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");
        }
开发者ID:Joncash,项目名称:HanboAOMClassLibrary,代码行数:27,代码来源:AsyncConnectionForm.cs

示例2: TCPSocket

        public TCPSocket(Socket from, bool socket_listening)
        {
            sock = from;
            listening = socket_listening;

            if (socket_listening)
            {
                IPEndPoint tmp = (IPEndPoint)sock.LocalEndPoint;
                port = (ushort)tmp.Port;
                ep = tmp;
            }
            else
            {
                IPEndPoint tmp = (IPEndPoint)sock.RemoteEndPoint;
                port = (ushort)tmp.Port;
                ep = tmp;
            }

            if (sock.Blocking == false)
            {
                sock.Blocking = true;
            }

            sock.ReceiveBufferSize = 1024 * 64; // 64 kb
            sock.SendBufferSize = 1024 * 64; // 64 kb
        }
开发者ID:Reve,项目名称:EVESharp,代码行数:26,代码来源:TCPSocket.cs

示例3: CruncherClient

 public CruncherClient(string serverAddress, int port)
 {
     mybuffer = new byte[MAX_BUFFER_SIZE];
     this.connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     this.server = Globals.ServerURL;
     this.port = System.Convert.ToInt32(Globals.ServerPort);
 }
开发者ID:mishkinf,项目名称:WordCrunchClients,代码行数:7,代码来源:CruncherClient.cs

示例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();
        }
开发者ID:qychen,项目名称:AprvSys,代码行数:25,代码来源:ClientCode.cs

示例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
 }
开发者ID:brandongrossutti,项目名称:DotCopter,代码行数:31,代码来源:Program.cs

示例6: connect

 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
开发者ID:kartikeyadubey,项目名称:share,代码行数:29,代码来源:Server.cs

示例7: 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);
         }
     }
 }
开发者ID:MohammedAbuissa,项目名称:Client_Server,代码行数:35,代码来源:UDPServer.cs

示例8: 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 { }
            }
        }
开发者ID:jiashida,项目名称:super-trojan-horse,代码行数:34,代码来源:BroadcastScan.cs

示例9: Recepteur

 /// <summary>
 /// Constructeur
 /// </summary>
 /// <param name="port">Port d'ecoute</param>
 /// <param name="cl"></param>
 public Recepteur(int port, Game1 cl)
 {
     this._client = cl;
     this._portReception = port;
     this._ip = GestionReseau.GetMyLocalIp();
     _reception = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
开发者ID:Chapelin,项目名称:XNAGitTest,代码行数:12,代码来源:Recepteur.cs

示例10: SetSocketOption

 protected static int SetSocketOption(Socket socket, SocketOptionLevel level, SocketOptionName name, int value)
 {
     if (((int)socket.GetSocketOption(level, name)) == value)
         return value;
     socket.SetSocketOption(level, name, value);
     return (int)socket.GetSocketOption(level, name);
 }
开发者ID:ByteSempai,项目名称:Ubiquitous,代码行数:7,代码来源:NetworkUtils.cs

示例11: Connect

        /// <summary>
        /// Connects to the node debugger.
        /// </summary>
        public void Connect() {
            Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Socket.NoDelay = true;
            Socket.Connect(new DnsEndPoint(_hostName, _portNumber));

            StartListenerThread();
        }
开发者ID:CforED,项目名称:Node.js-Tools-for-Visual-Studio,代码行数:10,代码来源:NodeConnection.cs

示例12: MessageParser

 public MessageParser(Socket serverSocket, Messaging parent)
 {
     this.threadSocket = serverSocket;
     this.parent = parent;
     Thread messageParserThread = new Thread(RunThread);
     messageParserThread.Start();
 }
开发者ID:adesproject,项目名称:ADES,代码行数:7,代码来源:Messaging.cs

示例13: BluetoothListener

 /// <overloads>
 /// Initializes a new instance of the <see cref="BluetoothListener"/> class.
 /// </overloads>
 /// ----
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothListener"/> class
 /// to listen on the specified service identifier.
 /// </summary>
 /// <param name="service">The Bluetooth service to listen for.</param>
 /// <remarks>
 /// <para>
 /// An SDP record is published on successful <see cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/>
 /// to advertise the server.
 /// A generic record is created, containing the essential <c>ServiceClassIdList</c>
 /// and <c>ProtocolDescriptorList</c> attributes.  The specified service identifier is
 /// inserted into the former, and the RFCOMM Channel number that the server is
 /// listening on is inserted into the latter.  See the Bluetooth SDP specification
 /// for details on the use and format of SDP records.
 /// </para><para>
 /// If a SDP record with more elements is required, then use
 /// one of the other constructors that takes an SDP record e.g. 
 /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(System.Guid,InTheHand.Net.Bluetooth.ServiceRecord)"/>,
 /// or when passing it as a byte array 
 /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(System.Guid,System.Byte[],System.Int32)"/>.
 /// The format of the generic record used here is shown there also.
 /// </para><para>
 /// Call the <see cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/> 
 /// method to begin listening for incoming connection attempts.
 /// </para>
 /// </remarks>
 public BluetoothListener(Guid service)
 {
     InitServiceRecord(service);
     this.serverEP = new BluetoothEndPoint(BluetoothAddress.None, service);
     serverSocket = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);
     m_optionHelper = new BluetoothClient.SocketOptionHelper(serverSocket);
 }
开发者ID:intille,项目名称:mitessoftware,代码行数:37,代码来源:BluetoothListener.cs

示例14: 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);
            }
        }
开发者ID:jen20,项目名称:tcp-servers-talk,代码行数:35,代码来源:TcpClientConnector.cs

示例15: RecordOpenedSocket

        protected override bool RecordOpenedSocket(Socket sock)
        {
            ThreadTrackingStatistic.FirstClientConnectedStartTracking();
            GrainId client;
            if (!ReceiveSocketPreample(sock, true, out client)) return false;

            // refuse clients that are connecting to the wrong cluster
            if (client.Category == UniqueKey.Category.GeoClient)
            {
                if(client.Key.ClusterId != Silo.CurrentSilo.ClusterId)
                {
                    Log.Error(ErrorCode.GatewayAcceptor_WrongClusterId,
                        string.Format(
                            "Refusing connection by client {0} because of cluster id mismatch: client={1} silo={2}",
                            client, client.Key.ClusterId, Silo.CurrentSilo.ClusterId));
                    return false;
                }
            }
            else
            {
                //convert handshake cliendId to a GeoClient ID 
                if (!string.IsNullOrEmpty(Silo.CurrentSilo.ClusterId))
                {
                    client = GrainId.NewClientId(client.PrimaryKey, Silo.CurrentSilo.ClusterId);
                }
            }

            gateway.RecordOpenedSocket(sock, client);
            return true;
        }
开发者ID:osjimenez,项目名称:orleans,代码行数:30,代码来源:GatewayAcceptor.cs


注:本文中的Socket类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。