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


C# Socket.Connect方法代码示例

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


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

示例1: BluetoothStream

        public BluetoothStream(BluetoothDevice btdev)
        {
            socket = new Socket((AddressFamily)32, SocketType.Stream, (ProtocolType)3);
            byte[] btAddress = btdev.Address;
            try
            {
                BluetoothEndPoint btep = new BluetoothEndPoint(btAddress, guid_spp);
                utils.ddump("connecting to " + btdev.AddressStr);
                socket.Connect(btep);
                utils.ddump("connected! Create networkstream...");
                networkstream = new NetworkStream(socket, true);

                utils.ddump("starting threads...");
                thSend = new Thread(new ThreadStart(sendThread));
                thSend.Name = "SendThread"; thSend.IsBackground = true;
                thSend.Start();
                utils.ddump("Thread started: " + thSend.Name + ", " + thSend.ManagedThreadId.ToString("x08"));

                thRecv = new Thread(new ThreadStart(recvThread));
                thRecv.Name = "RecvThread"; thRecv.IsBackground = true;
                thRecv.Start();
                utils.ddump("Thread started: " + thRecv.Name + ", " + thRecv.ManagedThreadId.ToString("x08"));
            }
            catch (Exception ex)
            {
                connected = false;
                utils.ddump("BluetoothStream init failed with " + ex.Message);
            }
        }
开发者ID:hjgode,项目名称:btprint,代码行数:29,代码来源:BluetoothStream.cs

示例2: GetResponseFromQuoteCache

        private string GetResponseFromQuoteCache(string requestMessage)
        {
            var messageBytes = Encoding.ASCII.GetBytes(requestMessage);

            try
            {
                // Open a new socket
                var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sender.Connect(_quoteCacheHost, _quoteCachePort);

                // Send request
                int sentBytes = sender.Send(messageBytes);
                Log.DebugFormat(CultureInfo.InvariantCulture,
                    "Sent {0} bytes over socket to \"{1}\" on port {2}.", sentBytes, _quoteCacheHost, _quoteCachePort);

                // Wait for response
                var responseBuffer = new byte[ResponseBufferSize];
                int receivedBytes = sender.Receive(responseBuffer);
                Log.DebugFormat(CultureInfo.InvariantCulture,
                    "Received {0} bytes over socket from \"{1}\" on port {2}.", receivedBytes, _quoteCacheHost, _quoteCachePort);

                // Return response as string
                return Encoding.ASCII.GetString(responseBuffer);
            }
            catch (Exception ex)
            {
                throw new QuoteException(String.Format(CultureInfo.InvariantCulture,
                    "Encountered an error while trying to connect to the quote cache at \"{0}\" on port {1}.",
                    _quoteCacheHost, _quoteCachePort), ex);
            }
        }
开发者ID:sjlbos,项目名称:SENG462_DTS,代码行数:31,代码来源:SocketQuoteProvider.cs

示例3: link

		public bool link(int room){
			if (socket != null) unlink();//断开之前的连接
			socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket
			string r =room.ToString();
			try{
				window.write("连接到"+r+"中...");
                byte[] temp = Encoding.ASCII.GetBytes("{\"roomid\":"+r+ ",\"uid\":201510566613409}");//构造房间信息
                socket.Connect("dm.live.bilibili.com", 788);//连接到弹幕服务器
                //构造消息头
                byte[] head = { 0x00, 0x00, 0x00, (byte)(0x31+r.Length), 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01 };
                socket.Send(head);//发送消息头
				socket.Send(temp);//发送请求正文——房间信息
				socket.Send(re);//这个本来应该是用来获取人数的,但是长期不发送服务器会断开连接,这里是为了防止这样的情况发生
                if (!flag)//检查读弹幕线程是否在工作
                {
                    keeper = new Thread(keep_link);
                    keeper.IsBackground = true;
                    reader = new Thread(getdanmu);
                    reader.IsBackground = true;
                    reader.Start();
                    keeper.Start();
                }
				window.write("连接成功");
			}
			catch (InvalidCastException)
			{
				window.write("连接失败");
			}
			return true;
		}
开发者ID:thestarweb,项目名称:bilibilidan,代码行数:30,代码来源:dmReader.cs

示例4: 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;
        }
开发者ID:zacglenn,项目名称:GroupActivityFeed,代码行数:27,代码来源:GroupActivityFeedConnector.cs

示例5: mysocket

        public mysocket()
        {
            string line, ip;
            int port;
            string[] splits;
            // config file read
            StreamReader sr = new StreamReader("server_config");
            line = sr.ReadLine();
            splits = line.Split(' ');
            ip = splits[2];
            line = sr.ReadLine();
            splits = line.Split(' ');
            port = Convert.ToInt16(splits[2]);

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

            bool reconnect = true;
            while(reconnect){
                try
                {
                    s.Connect(ip, port);
                    handshake();
                    reconnect = false;
                }
                catch (System.Net.Sockets.SocketException)
                {
                    Console.WriteLine("try to connect again");
                }
            }
        }
开发者ID:bradyhau106,项目名称:pad_form,代码行数:30,代码来源:mysocket.cs

示例6: Authorize

        public static bool Authorize(string user, uint key)
        {
            try
            {
                Auth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    Auth.Connect(Configs.SERVER_IP, Configs.AUTH_PORT);
                }
                catch
                {
                    Console.WriteLine("Failed to send client data to game server");
                }

                Auth.Send(System.Text.Encoding.ASCII.GetBytes("(A)" + user + "," + key));
                Auth.Close();
            }
            catch (SocketException e)
            {
                Console.WriteLine("Exception Caught while connecting to game server: " + e.ErrorCode.ToString());
                return false;
            }
            return true;
        }
开发者ID:halo779,项目名称:EoEmu,代码行数:25,代码来源:AuthSocket.cs

示例7: btnStartMulti_Click

		private void btnStartMulti_Click(object sender, EventArgs e)
		{
			btnStopMulti_Click(this, EventArgs.Empty);

			_isMultiStart = true;
			var ipEndPoint = new IPEndPoint(IPAddress.Parse(txtMultiIp.Text), int.Parse(txtMultiPort.Text));
			var threadCount = int.Parse(txtMultiThreadCount.Text);

			for (var i = 0; i < threadCount; i++)
			{
				Task.Factory.StartNew(() =>
				{
					while (_isMultiStart)
					{
						var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
						try
						{
							_socketList.Add(socket);

							socket.Connect(ipEndPoint);
							socket.Close();
						}
						catch (Exception)
						{
						}
						finally
						{
							_socketList.Remove(socket);
						}
					}
				});
			}
		}
开发者ID:josh-jeong,项目名称:Rhyme.Tools,代码行数:33,代码来源:frmSocket.cs

示例8: sendFile

        public static void sendFile(string hostname, int port, string filepath) {
            FileInfo file = new FileInfo(filepath);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(hostname, port);

            int length = (int)file.Length;
            using(FileStream reader = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None)) {
                //socket.Send(BitConverter.GetBytes(length));
                string fileName = Path.GetFileName(filepath);
                Byte[] fn_bytes = Encoding.Default.GetBytes(fileName);
                socket.Send(Methods.i2b(fn_bytes.Length));
                socket.Send(fn_bytes);

                socket.Send(Methods.i2b(length));
                long send = 0L;
                ////Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
                byte[] buffer = new byte[BufferSize];
                int read, sent;
                //断点发送 在这里判断设置reader.Position即可
                while((read = reader.Read(buffer, 0, BufferSize)) !=0) {
                    sent = 0;
                    while((sent += socket.Send(buffer, sent, read, SocketFlags.None)) < read) {
                        send += (long)sent;
                        //Console.WriteLine("Sent " + send + "/" + length + ".");//进度
                    }
                }
                //Console.WriteLine("Send finish.");
            }
        }
开发者ID:freaky0112,项目名称:SocketTest,代码行数:29,代码来源:Transfer.cs

示例9: SendCmdRequest

        public bool SendCmdRequest(CmdRequest request)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect("127.0.0.1", Port);
                using (NetworkStream stream = new NetworkStream(socket))
                {
                    using (BsonWriter writer = new BsonWriter(stream))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Serialize(writer, request);
                        writer.Flush();
                        writer.Close();
                    }
                   
                    stream.Close();
                }
            }
            catch(Exception ex)
            {
                Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex);
                return false;
            }

            return true;
        }
开发者ID:intech,项目名称:Checker,代码行数:28,代码来源:ThreadProcess.cs

示例10: reConnect

        public void reConnect()
        {
            clientSocket.Close();
            clientSocket = null;
            sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0     

            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                System.Threading.Thread tt = new System.Threading.Thread(delegate()
                {
                    try
                    {
                        clientSocket.Connect(ip, port);
                    }
                    catch (Exception ee)
                    {
                        //MessageBox.Show(ee.Message + "\r\n From:" + this);
                    }
                });
                tt.Start();

            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message + "\r\n From:" + this);
            }
        }
开发者ID:Season02,项目名称:MK2.0,代码行数:29,代码来源:socket.cs

示例11: GDBDebugger

        public GDBDebugger()
        {
            string gdbHost = Application.Session.Properties["GDBDebugger.Host"];
            int    gdbPort = int.Parse(Application.Session.Properties["GDBDebugger.Port"]);

            // Initialise locals
            this.breakpoints = new List<Breakpoint>();

            // Set the current architecture to the session one
            this.CurrentArchitecture = Application.Session.Architecture;

            // Connect to GDB stub
            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            sock.Connect(gdbHost, gdbPort);

            // Make empty initial register listing
            this.Registers  = new RegisterSet(new Register[0], new bool[0], new bool[0]);

            // Create connector and begin debugging
            this.connector = new GDBConnector(sock);
            try
            {
                this.connector.EstablishConnection();
                this.CurrentStatus = DebugStatus.Suspended;

                this.connector.Paused += OnGDBPaused;
            }
            catch
            {
                this.CurrentStatus = DebugStatus.Disconnected;
                this.connector.Dispose();
                throw;
            }
        }
开发者ID:jsren,项目名称:DebugOS,代码行数:34,代码来源:GDBDebugger.cs

示例12: CSocket

 public CSocket(IPEndPoint _endPoint, SocketPool _pool, SocketPoolProfile config)
 {
     socketConfig = config;
     endpoint = _endPoint;
     pool = _pool;
     System.Net.Sockets.Socket _socket = new System.Net.Sockets.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();
 }
开发者ID:ZouTrankil,项目名称:Gaea,代码行数:27,代码来源:CSocket.cs

示例13: PostAction

        private static bool PostAction(Proxy p, Server server, Action action)
        {
            var instance = p.Instance;
            // if we can't issue any commands, bomb out
            if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty()) return false;

            var loginInfo = instance.AdminUser + ":" + instance.AdminPassword;
            var haproxyUri = new Uri(instance.Url);
            var requestBody = string.Format("s={0}&action={1}&b={2}", server.Name, action.ToString().ToLower(), p.Name);
            var requestHeader = string.Format("POST {0} HTTP/1.1\r\nHost: {1}\r\nContent-Length: {2}\r\nAuthorization: Basic {3}\r\n\r\n",
                haproxyUri.AbsolutePath, haproxyUri.Host, Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length, Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo)));

            try
            {
                var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(haproxyUri.Host, haproxyUri.Port);
                socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody));

                var responseBytes = new byte[socket.ReceiveBufferSize];
                socket.Receive(responseBytes);

                var response = Encoding.UTF8.GetString(responseBytes);
                instance.PurgeCache();
                return response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303");
            }
            catch (Exception e)
            {
                Current.LogException(e);
                return false;
            }
        }
开发者ID:JonBons,项目名称:Opserver,代码行数:31,代码来源:HAProxyAdmin.cs

示例14: CreateEndPoint

		protected static Mono.Unix.UnixEndPoint CreateEndPoint (string path)
		{
			if (path == null)
				throw new ArgumentNullException ("path");

			Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint (
				                            path);

			if (System.IO.File.Exists (path)) {
				System.Net.Sockets.Socket conn =
					new System.Net.Sockets.Socket (
						System.Net.Sockets.AddressFamily.Unix,
						System.Net.Sockets.SocketType.Stream,
						System.Net.Sockets.ProtocolType.IP);

				try {
					conn.Connect (ep);
					conn.Close ();
					throw new InvalidOperationException (
						string.Format (CultureInfo.CurrentCulture,
							Strings.UnixSocket_AlreadyExists,
							path));
				} catch (System.Net.Sockets.SocketException) {
				}

				System.IO.File.Delete (path);
			}

			return ep;
		}
开发者ID:qinfengzhu,项目名称:HyperFastCgi,代码行数:30,代码来源:UnixSocket.cs

示例15: ConnectAndGetWebServerRequest

        protected WebServerSocketRequest ConnectAndGetWebServerRequest(ushort requestId)
        {
            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Connect(ListenOn, ListenPort);

            return new WebServerSocketRequest(sock, requestId);
        }
开发者ID:knocte,项目名称:Fos,代码行数:7,代码来源:SocketTests.cs


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