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


C# Socket.Close方法代码示例

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


在下文中一共展示了Socket.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

    static void Main()
    {
        var sk = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            EndPoint my = new IPEndPoint(IPAddress.Loopback,1233);
            sk.BeginReceiveFrom(new byte[1500], 0, 1500, SocketFlags.None, ref my, new AsyncCallback(ReceiveCallback), null);
            sk.Close();
    }
开发者ID:tigerhu67,项目名称:monobuildtools,代码行数:8,代码来源:lucas.cs

示例2: Main

 static void Main(string[] args)
 {
     //设定服务器IP地址
     IPAddress ip = IPAddress.Parse ("127.0.0.1");
     Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try {
         clientSocket.Connect (new IPEndPoint (ip, 8885)); //配置服务器IP与端口
         Console.WriteLine ("连接服务器成功");
     } catch {
         Console.WriteLine ("连接服务器失败,请按回车键退出!");
         return;
     }
     //通过clientSocket接收数据
     int receiveLength = clientSocket.Receive (result);
     Console.WriteLine ("接收服务器消息:{0}", Encoding.ASCII.GetString (result, 0, receiveLength));
     //通过 clientSocket 发送数据
     for (int i = 0; i < 10; i++) {
         try {
             Thread.Sleep (1000);    //等待1秒钟
             string sendMessage = "client send Message Hellp" + DateTime.Now;
             clientSocket.Send (Encoding.ASCII.GetBytes (sendMessage));
             Console.WriteLine ("向服务器发送消息:{0}" + sendMessage);
         } catch {
             clientSocket.Shutdown (SocketShutdown.Both);
             clientSocket.Close ();
             break;
         }
     }
     Console.WriteLine ("发送完毕,按回车键退出");
     Console.ReadLine ();
 }
开发者ID:hebbaixue99,项目名称:XJDemoServer,代码行数:31,代码来源:SocketClientDemo.cs

示例3: Close_Timeout

 public static void Close_Timeout(int timeout)
 {
     using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         s.Close(timeout);
     }
 }
开发者ID:Corillian,项目名称:corefx,代码行数:7,代码来源:Close.cs

示例4: Main

	public static void Main(String []argv)
	{
		IPAddress ip = IPAddress.Loopback;
		Int32 port=1800;
		if(argv.Length>0)
			port = Int32.Parse(argv[0]);	
		IPEndPoint ep = new IPEndPoint(ip,port);
		Socket ss = new Socket(AddressFamily.InterNetwork , 
			SocketType.Stream , ProtocolType.Tcp);
		try
		{
			ss.Bind(ep);
		}
		catch(SocketException err)
		{
			Console.WriteLine("** Error : socket already in use :"+err);
			Console.WriteLine("           Please wait a few secs & try");	
		}
		ss.Listen(-1);
		Console.WriteLine("Server started and running on port {0}.....",port);
		Console.WriteLine("Access URL http://localhost:{0}",port);
		Socket client = null;
		while(true)
		{
			client=ss.Accept();
			SocketMessenger sm=new SocketMessenger(client);
			sm.Start();
		}
		Console.WriteLine(client.LocalEndPoint.ToString()+" CONNECTED ");
		ss.Close();
	}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:31,代码来源:httpsrv.cs

示例5: Close_BadTimeout_Throws

 public static void Close_BadTimeout_Throws()
 {
     using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => s.Close(-2));
     }
 }
开发者ID:Corillian,项目名称:corefx,代码行数:7,代码来源:Close.cs

示例6: AttemptConnection

    public void AttemptConnection( string ipAddressString, string portString )
    {
        debugLog.ReceiveMessage ( "\tAttempting Connection to " + ipAddressString + " on " + portString );

        connecting = true;
        connectionType = ConnectionType.Connecting;
        debugLog.ReceiveMessage ( "\tConnection Type Set to Connecting" );

        try
        {

            IPAddress ipAddress = Dns.GetHostEntry ( ipAddressString ).AddressList[0];
            IPEndPoint remoteEndPoint = new IPEndPoint ( ipAddress, Convert.ToInt32 ( portString ));

            Socket client = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

            client.BeginConnect ( remoteEndPoint, new AsyncCallback ( ConnectCallback ), client );

            Send ( client, "This is a test<EOF>" );

            Receive ( client );

            UnityEngine.Debug.Log ( "Response received : " + response );

            client.Shutdown ( SocketShutdown.Both );
            client.Close ();
        } catch ( Exception connectionError )
        {

            UnityEngine.Debug.LogError ( connectionError );
        }
    }
开发者ID:2CatStudios,项目名称:TradingCardGame,代码行数:32,代码来源:NetworkManager.cs

示例7: run

        public void run()
        {
            running = true;
            try
            {
                Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("192.168.0.14");
                System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 1234);
                soc.Connect(remoteEP);
                soc.Send(System.Text.Encoding.ASCII.GetBytes("Output\n"));
                while (running)
                {
                    byte[] buffer = new byte[1024];
                    int iRx = soc.Receive(buffer);
                    char[] chars = new char[iRx];

                    System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                    int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
                    System.String recv = new System.String(chars);
                    //Console.WriteLine(recv);
                    Debug.Log(recv);
                }
                soc.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
开发者ID:James534,项目名称:ServerClient,代码行数:29,代码来源:ListenClient.cs

示例8: StartClient

    public static void StartClient()
    {
        try
        {
            byte[] bytes = File.ReadAllBytes("c:\\file.bin");
            string x = Convert.ToBase64String(bytes);

            IPHostEntry ipHostInfo = Dns.Resolve(Environment.MachineName);
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port);

            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, ConnectCallback, client);
            ConnectDone.WaitOne();

            Send(client, x + "<EOF>");
            SendDone.WaitOne();

            Receive(client);
            ReceiveDone.WaitOne();

            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            throw;
        }
    }
开发者ID:EttienneS,项目名称:Contingency,代码行数:29,代码来源:Program.cs

示例9: Sync_init

    public static void Sync_init()
    {
        sync_srv_state = true;
        Syncsck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Syncsck.Bind(new IPEndPoint(IPAddress.Parse(RmIp), SyncPort));
        Syncsck.Listen(5);
        Syncsck.ReceiveTimeout = 12000;
        while (true)
        {
            try
            {
                Cmdsck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Cmdsck.Connect(new IPEndPoint(IPAddress.Parse(RmIp), CmdPort));
                sync_srv_state = true;
            }
            catch
            {
                sync_srv_state = false;
                Console.WriteLine("Con. False");
                Thread.Sleep(5000);
            }
            if (sync_srv_state == true)
            {
                Thread Syncproc = new Thread(Sync_srv);
                Syncproc.Start();
                Thread.Sleep(5000);
                while (sync_srv_state == true) { Thread.Sleep(1000); }
                Cmdsck.Close();
            }
        }

    }
开发者ID:frengc0641,项目名称:ConsoleT,代码行数:32,代码来源:Sync.cs

示例10: send

    //static void Main(string[] args, int a)
    public static void send()
    {
        String name = Id.name;
            String a2 = link.a.ToString();
            int y = 9;
            String a3 = y.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();
        // all the data will  be sent in one buffer.
            byte[] buffer = Encoding.Default.GetBytes(name + a2 + a3);

            acc.Send(buffer, 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();
    }
开发者ID:rickoskam,项目名称:ShepherdGame,代码行数:28,代码来源:PostData.cs

示例11: fUniversal

 //Universal function
 public string fUniversal(string sAction, string sUser = "", string sArgsList = "")
 {
     try
     {
         Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create TCP/IP socket.
         connectDone.Reset();
         client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); // Connect to the remote endpoint.
         connectDone.WaitOne();
         if (!ReferenceEquals(myException, null)) //No connection present
             throw (myException);
         sendDone.Reset();
         Send(client, sAction + "," + sUser + "," + sArgsList); // Send data to the remote device.
         sendDone.WaitOne();
         receiveDone.Reset();
         Receive(client); // Receive the response from the remote device.
         receiveDone.WaitOne();
         client.Shutdown(SocketShutdown.Both); //End connection
         client.Close();
         return response;
     }
     catch (Exception ex)
     {
         log.Debug(ex.ToString());
         throw ex;
     }
 }
开发者ID:samardzicnenad,项目名称:CooperUnion,代码行数:27,代码来源:AsynchronousClient.cs

示例12: InsertObject

    public int InsertObject(byte[] obj, float[] coord)
    {
        int answer = -5;
        BinaryFormatter bf = new BinaryFormatter ();
        MemoryStream ms = new MemoryStream ();
        byte[] instream;

        Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect (new IPEndPoint(IPAddress.Parse("10.9.169.218"), 1234));

        InsertQuery iq = new InsertQuery(new AskObject(coord, 0, 0, obj, 0));

        ms = new MemoryStream();
        bf.Serialize(ms, iq);
        socket.Send(ms.ToArray());

        instream = new byte[100000];
        socket.Receive(instream);
        ms = new MemoryStream (instream);
        object ans = bf.Deserialize (ms);
        if (ans is BoolIntResult) {
            BoolIntResult ans2 = (BoolIntResult)ans;
            if (ans2.boolVal == true)
                answer = ans2.integer;
        } else {
            Debug.Log ("Wrong confirmation packet.");
        }
        socket.Close();
        return answer;
    }
开发者ID:ASchvartzman,项目名称:518Project-ASK,代码行数:30,代码来源:Client.cs

示例13: Main

	static void Main (string [] args)
	{
		int port;

		Random random = new Random ();
		Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

		do {
			port = random.Next (0xc350, 0xffdc);
			IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, port);
			try {
				socket.Bind (localEP);
				break;
			} catch {
			}
		} while (true);

		socket.Close ();

		IPEndPoint LocalEP = new IPEndPoint (IPAddress.Loopback, port);
		Socket ListeningSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		ListeningSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
		ListeningSocket.Bind (LocalEP);
		ListeningSocket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
			new MulticastOption (IPAddress.Parse ("239.255.255.250"), IPAddress.Loopback));
		ListeningSocket.Close ();
	}
开发者ID:mono,项目名称:gert,代码行数:27,代码来源:test.cs

示例14: CleanupClient

 private static void CleanupClient(Socket clientTcpSocket)
 {
     lock (_coarseLock) {
         _clientSockets.Remove(clientTcpSocket);
     }
     _logger.Log (string.Format ("cleaned up client with TCP socket {0}", Utils.IPAddressToString (clientTcpSocket.RemoteEndPoint)));
     clientTcpSocket.Close ();
 }
开发者ID:BluBambu,项目名称:MultiVoxel,代码行数:8,代码来源:Server.cs

示例15: MakeRequestInternal

    private void MakeRequestInternal(string message)
    {
        // Data buffer for incoming data.
        byte[] bytes = new byte[Transport.PacketSize];

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            IPAddress ipAddress = IpHelper.ServerIp;
            IPEndPoint remoteEP = new IPEndPoint(ipAddress,port);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                sender.Connect(remoteEP);

                byte[] msg = Encoding.ASCII.GetBytes(message+Transport.EndFlag);
                // Send the data through the socket.
                int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);

                var data = Encoding.ASCII.GetString(bytes,0,bytesRec);
                _clientProtocol.ProcessResponse(data);

                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }
            catch (ArgumentNullException ane)
            {
                _clientProtocol.NotifyError();
                Debug.Log(ane.ToString());
            }
            catch (SocketException se)
            {
                _clientProtocol.NotifyError();
                Debug.Log(se.ToString());
            }
            catch (Exception e)
            {
                _clientProtocol.NotifyError();
                Debug.Log(e.ToString());
            }
        }
        catch (Exception e)
        {
            _clientProtocol.NotifyError();
            Debug.Log( e.ToString());
        }
    }
开发者ID:jericho17,项目名称:BallsTestTask,代码行数:57,代码来源:ClientTransport.cs


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