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"); } }
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(); }
static void Main(string[] args) { IPAddress[] addresses = Dns.GetHostAddresses("38.98.173.2"); //IPAddress[] addresses = Dns.GetHostAddresses("127.0.0.1"); IPEndPoint _ipEndpoint = new IPEndPoint(addresses[0], 58642); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("38.98.173.2"), 58642); Socket _socket = new Socket(_ipEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = _socket.BeginConnect(_ipEndpoint, null, null); bool success = result.AsyncWaitHandle.WaitOne(2000, true); if (!success) { _socket.Close(); Console.WriteLine("failed to connect"); //throw new ApplicationException("Timeout trying to connect to server!"); } if (_socket.Connected) { Console.WriteLine("connected!"); //send a byte to let the server know that this is the data loader program communicating with it byte[] clientTypeByte = new byte[1024]; for(int i=0;i<1024;i++) clientTypeByte[i] = (byte)(i%256); _socket.Send(clientTypeByte); byte[] dataFromServer = new byte[1024]; int bytesReceived = _socket.Receive(dataFromServer); _socket.Close(); } Console.ReadLine(); }
public JTAGSerialStream2(string Cable, int Device, int Instance) { try { Socket SerialListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint SerialEP = new IPEndPoint(IPAddress.Any, 0); SerialListenSocket.Bind(SerialEP); SerialListenSocket.Listen(1); SerialEP = (IPEndPoint)SerialListenSocket.LocalEndPoint; SerialProcess = new Process(); SerialProcess.StartInfo.FileName = "quartus_stp"; SerialProcess.StartInfo.Arguments = String.Format("-t serial.tcl \"{0}\" {1} {2} {3}", Cable, Device, Instance, SerialEP.Port); SerialProcess.EnableRaisingEvents = true; SerialProcess.Exited += delegate(object Sender, EventArgs e) { if (SerialListenSocket != null) SerialListenSocket.Close(); }; SerialProcess.Start(); SerialSocket = SerialListenSocket.Accept(); SerialListenSocket.Close(); SerialListenSocket = null; } catch (System.ComponentModel.Win32Exception e) { throw new JTAGException(String.Format("Error starting JTAG serial process: {0}", e.Message)); } }
/// <summary> /// Try to update both system and RTC time using the NTP protocol /// </summary> /// <param name="TimeServer">Time server to use, ex: pool.ntp.org</param> /// <param name="GmtOffset">GMT offset in minutes, ex: -240</param> /// <returns>Returns true if successful</returns> public DateTime NTPTime(string TimeServer, int GmtOffset = 0) { Socket s = null; DateTime resultTime = DateTime.Now; try { EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123); s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] ntpData = new byte[48]; Array.Clear(ntpData, 0, 48); ntpData[0] = 0x1B; // Set protocol version s.SendTo(ntpData, rep); // Send Request if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout { s.ReceiveFrom(ntpData, ref rep); // Receive Time byte offsetTransmitTime = 40; ulong intpart = 0; ulong fractpart = 0; for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i]; for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i]; ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L); s.Close(); resultTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond); Utility.SetLocalTime(resultTime.AddMinutes(GmtOffset)); } s.Close(); } catch { try { s.Close(); } catch { } } return resultTime; }
public void RefreshTorIdentity() { Socket server = null; try { IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Connect(ip); // Please be sure that you have executed the part with the creation of an authentication hash, described in my article! server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"johnsmith\"" + Environment.NewLine)); byte[] data = new byte[1024]; int receivedDataLength = server.Receive(data); string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine)); data = new byte[1024]; receivedDataLength = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); if (!stringData.Contains("250")) { Console.WriteLine("Unable to signal new user to server."); server.Shutdown(SocketShutdown.Both); server.Close(); } } finally { server.Close(); } }
private void ProcessConnection(Socket socket) { const int minCharsCount = 3; const int charsToProcess = 64; const int bufSize = 1024; try { if (!socket.Connected) return; var data = ""; while (true) { var bytes = new byte[bufSize]; var recData = socket.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, recData); if (data.Length >= charsToProcess) { var str = data.Take(charsToProcess); var charsTable = str.Distinct() .ToDictionary(c => c, c => str.Count(x => x == c)); if (charsTable.Count < minCharsCount) { var message = $"Server got only {charsTable.Count} chars, closing connection.<EOF>"; socket.Send(Encoding.ASCII.GetBytes(message)); socket.Close(); break; } var result = String.Join(", ", charsTable.Select(c => $"{c.Key}: {c.Value}")); Console.WriteLine($"Sending {result}\n"); socket.Send(Encoding.ASCII.GetBytes(result + "<EOF>")); data = String.Join("", data.Skip(charsToProcess)); } } } finally { socket.Close(); } }
/// <summary> /// This code is used to connect to a TCP socket with timeout option. /// </summary> /// <param name="endPoint">IP endpoint of remote server</param> /// <param name="timeoutMs">Timeout to wait until connect</param> /// <returns>Socket object connected to server</returns> public static Socket ConnectToServerWithTimeout(EndPoint endPoint, int timeoutMs) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.Blocking = false; socket.Connect(endPoint); socket.Blocking = true; return socket; } catch (SocketException socketException) { if (socketException.ErrorCode != 10035) { socket.Close(); throw; } if (!socket.Poll(timeoutMs * 1000, SelectMode.SelectWrite)) { socket.Close(); throw new NGRIDException("The host failed to connect. Timeout occured."); } socket.Blocking = true; return socket; } }
public bool addClass(string hostName, int hostPort, string appName, string className, string classTitle) { IPAddress host = IPAddress.Parse(hostName); IPEndPoint hostep = new IPEndPoint(host, hostPort); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { sock.Connect(hostep); } catch (SocketException e) { Console.WriteLine("Problem connecting to host"); Console.WriteLine(e.ToString()); if (sock.Connected) { sock.Close(); } } try { response = sock.Send(Encoding.ASCII.GetBytes("type=SNP#?version=1.0#?action=add_class#?app=" + appName + "#?class=" + className + "#?title=" + classTitle)); response = sock.Send(Encoding.ASCII.GetBytes("\r\n")); } catch (SocketException e) { Console.WriteLine(e.ToString()); } sock.Close(); return true; }
private void Connect() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = SendTimeout, ReceiveTimeout = ReceiveTimeout }; try { if (ConnectTimeout == 0) { socket.Connect(Host, Port); } else { var connectResult = socket.BeginConnect(Host, Port, null, null); connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true); } if (!socket.Connected) { socket.Close(); socket = null; return; } Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024); if (Password != null) SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes()); db = 0; var ipEndpoint = socket.LocalEndPoint as IPEndPoint; clientPort = ipEndpoint != null ? ipEndpoint.Port : -1; lastCommand = null; lastSocketException = null; LastConnectedAtTimestamp = Stopwatch.GetTimestamp(); if (isPreVersion1_26 == null) { isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0; } if (ConnectionFilter != null) { ConnectionFilter(this); } } catch (SocketException ex) { if (socket != null) socket.Close(); socket = null; HadExceptions = true; var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex); log.Error(throwEx.Message, ex); throw throwEx; } }
public async Task<IEnumerable<string>> ScanAsync() { var result = new List<string>(); var vcmd = "host:version"; var okay = "OKAY0004001d"; foreach(var item in NetworkInterface.GetAllNetworkInterfaces()) { if(item.NetworkInterfaceType == NetworkInterfaceType.Loopback || item.OperationalStatus != OperationalStatus.Up) continue; this.LogDebug("Scanning network interface: {0}", item.Description); UnicastIPAddressInformationCollection UnicastIPInfoCol = item.GetIPProperties().UnicastAddresses; foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol) { try { var gateway = item.GetIPProperties().GatewayAddresses.First().Address; var range = new IPAddressRange("{0}/{1}".With(gateway, UnicatIPInfo.IPv4Mask)); foreach(var ip in range.Addresses.Skip(110)) { for(var port = 5550; port < 5560; port++) { this.LogDebug("Connecting to {0}:{1}", ip, port); using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { try { socket.Blocking = true; var aresult = socket.BeginConnect(ip, port, null, null); bool success = aresult.AsyncWaitHandle.WaitOne(200, true); if(!success) { this.LogWarn("Connection Timeout"); socket.Close(); continue; } this.LogDebug("Connection successful: {0}:{1}", ip, port); var b = new byte[12]; var data = "{0}{1}\n".With(vcmd.Length.ToString("X4"), vcmd).GetBytes(); var count = socket.Send(data, 0, data.Length, SocketFlags.None); if(count == 0) { throw new InvalidOperationException("Unable to send version command to adb"); } socket.ReceiveBufferSize = 4; count = socket.Receive(b,0,4, SocketFlags.None); var msg = b.GetString(); if(string.Compare(msg, okay, false) == 0) { result.Add("{0}:{1}".With(ip.ToString(), port)); break; } socket.Close(); } catch(InvalidOperationException ioe) { this.LogError(ioe.Message, ioe); } } } } } catch(Exception ex) { this.LogError(ex.Message, ex); } } } return result; }
private string gsProgrammerMail = ConfigurationManager.AppSettings.Get("ProgrammerMail"); //從AppConfig讀取「ProgrammerMail」參數 #endregion Fields #region Methods /// <summary> /// 連線或斷線至ModBusToEthernet設備 /// iStatus = 0,則連線 /// iStatus = 1,則斷線 /// </summary> /// <param name="iStatus">0為連線、1為斷線</param> /// <param name="sIP">設備的IP位址</param> /// <param name="sIPPort">設備的IP_Port</param> public bool LinkEQP(int iStatus, string sIP, string sIPPort, Socket gWorkSocket) { bool blFlag = false; try { switch (iStatus) { case 0: // Set the timeout for synchronous receive methods to // 1 second (1000 milliseconds.) gWorkSocket.ReceiveTimeout = giReceiveTimeout * 1000; // Set the timeout for synchronous send methods // to 1 second (1000 milliseconds.) gWorkSocket.SendTimeout = giSendTimeout * 1000; if (gWorkSocket.Connected == true) { gWorkSocket.Shutdown(SocketShutdown.Both); gWorkSocket.Close(); } else if (gWorkSocket.Connected == false) { gWorkSocket.Connect(sIP, Convert.ToInt32(sIPPort)); if ((gWorkSocket.Connected == true)) { //System.Threading.Thread.Sleep(150); gLogger.Trace("ModbusRTU--成功連結 to:" + sIP); } } blFlag = true; break; case 1: if ((gWorkSocket.Connected == true)) { gWorkSocket.Shutdown(SocketShutdown.Both); gWorkSocket.Close(); //System.Threading.Thread.Sleep(150); gLogger.Trace("ModbusRTU--取消連線 to:" + sIP); } blFlag = false; break; } } catch (Exception ex) { gLogger.ErrorException("ModbusTCP.LinkEQP:", ex); if (gWorkSocket.Connected) { gWorkSocket.Shutdown(SocketShutdown.Both); gWorkSocket.Close(); } throw ex; } return blFlag; }
public static void StartClient(string ip, string data) { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = IPAddress.Parse(ip); IPEndPoint remoteEP = new IPEndPoint(ipAddress, 15001); // 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); Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString()); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes(data + "<EOF>"); // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.WriteLine("finish " + DateTime.Now); } catch (Exception e) { sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private void btnEnter_Click(object sender, EventArgs e) { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666); clientSocket.SendBufferSize = 1024; clientSocket.ReceiveBufferSize = 1024; try { clientSocket.Connect(ipep); Regex reg = new Regex(@"^[a-zA-Z0-9_]+$"); userName = textName.Text; //Check whether the name only consisits of letters,numbers,underlines if (reg.IsMatch(userName)) { byte[] nameByte = new byte[1024]; Encoding.UTF8.GetBytes(userName,0,userName.Length,nameByte,0); clientSocket.Send(nameByte); byte[] answerByte = new byte[1024]; clientSocket.Receive(answerByte); string answer = Encoding.UTF8.GetString(answerByte).Trim(new char[] { '\0' }); if (answer == "NameErr") { //fail to log in MessageBox.Show(userName + "has been used.\r\nPlease try another one."); textName.Clear(); clientSocket.Close(); } else if (answer == "NameSuc") { //log in successfully this.DialogResult = DialogResult.OK; } } else { MessageBox.Show("Only letters,numbers,underlines are allowed"); textName.Clear(); clientSocket.Close(); } } catch (SocketException) { //When the server isn't started MessageBox.Show("Disconnected to the server"); this.Close(); Application.Exit(); } }
public static bool verify(string address) { string[] host = (address.Split('@')); string hostname = host[1]; //string hostStr = "smtp.net4india.com"; IPHostEntry IPhst = Dns.GetHostEntry(hostname); //Dns.GetHostByName IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0],25); Socket s = new Socket(endPt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); s.Connect(endPt); //Attempting to connect if (!Check_Response(s, SMTPResponse.CONNECT_SUCCESS)) { s.Close(); return false; } //HELO server Senddata(s, string.Format("HELO {0}\r\n", Dns.GetHostName())); if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS)) { s.Close(); return false; } //Identify yourself //Servers may resolve your domain and check whether //you are listed in BlackLists etc. Senddata(s, string.Format("MAIL From: {0}\r\n", "*****@*****.**")); if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS)) { s.Close(); return false; } //Attempt Delivery (I can use VRFY, but most //SMTP servers only disable it for security reasons) Senddata(s, address); if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS)) { s.Close(); return false; } return (true); }
private void Connect() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = SendTimeout }; try { socket = GetSocketCanConnect(); if (!socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Close(); socket = null; return; } Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024); if (Password != null) SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes()); db = 0; var ipEndpoint = socket.LocalEndPoint as IPEndPoint; clientPort = ipEndpoint != null ? ipEndpoint.Port : -1; lastCommand = null; lastSocketException = null; LastConnectedAtTimestamp = Stopwatch.GetTimestamp(); if (isPreVersion1_26 == null) { isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0; //force version reload log.DebugFormat("redis-server Version: {0}", isPreVersion1_26); } } catch (SocketException ex) { if (socket != null) socket.Close(); socket = null; HadExceptions = true; var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex); log.Error(throwEx.Message, ex); throw throwEx; } }
public FTPClient(string Server, int Port = 21, string Username = "******", string Password = @"*****@*****.**") { PasvMode = true; #if DEBUG Console.WriteLine(@"FTP: Connecting to {0}...",Server); #endif IPAddress addr; try { CommandSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); addr = Dns.GetHostEntry(Server).AddressList[0]; CommandSocket.Connect(addr,Port); } catch (Exception ex) { if (CommandSocket != null && CommandSocket.Connected) CommandSocket.Close(); throw new FtpException("Couldn't connect to remote server", ex); } #if DEBUG Console.WriteLine(@"FTP: TCP connection estabilished " + Server); #endif ReadResponse(); if (ResponseCode != 220) { //close throw new FtpException(Response.Substring(4),ResponseCode,"connnect"); } #if DEBUG Console.WriteLine(@"FTP: Authorizing as {0}, {1}", Username, Password); #endif SendCommand("USER " + Username); if (!(ResponseCode == 331 || ResponseCode == 230 || ResponseCode == 220)) { //close throw new FtpException(Response.Substring(4),ResponseCode,"USER"); } if (ResponseCode != 230) { SendCommand("PASS " + Password); if (!(ResponseCode == 230 || ResponseCode == 202)) { //close throw new FtpException(Response.Substring(4),ResponseCode,"PASS"); } } #if DEBUG Console.WriteLine(@"FTP: FTP connection estabilished " + Server); #endif }
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(); }
//Main static void Main(string[] args) { ILog log = LogManager.GetLogger(typeof(Program)); //Added Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; svrSkt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); svrSkt.Bind(new IPEndPoint(IPAddress.Any, 2050)); svrSkt.Listen(0xff); svrSkt.BeginAccept(Listen, null); Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Saving Please Wait..."); svrSkt.Close(); foreach (var i in RealmManager.Clients.Values.ToArray()) { i.Save(); i.Disconnect(); } Console.WriteLine("\nClosing..."); Thread.Sleep(100); Environment.Exit(0); }; Console.ForegroundColor = ConsoleColor.Green; Console.Title = "Server Engine"; Console.WriteLine("Accepting connections at port " + port + "."); HostPolicyServer(); RealmManager.CoreTickLoop(); }
void ListenThreadFunc() { Socket listenSocket = null; try { listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Any, _port); listenSocket.Bind(ep); LogThread.Log("ListenThread: Listening on port " + _port, LogThread.LogMessageType.Normal, true); while (true) { listenSocket.Listen(10); Socket conn = listenSocket.Accept(); if (conn != null && OnConnectionAccepted != null) { LogThread.Log("ListenThread: Connection Accepted", LogThread.LogMessageType.Debug); OnConnectionAccepted(this, new SocketArg(conn)); } } } catch (Exception ex) { LogThread.Log(ex.ToString(), LogThread.LogMessageType.Error, true); listenSocket.Close(); _theThread = null; } }
private void DataArrival(System.IAsyncResult oResult) { log.Info("Data Arrive"); System.Net.Sockets.Socket oSocket = (System.Net.Sockets.Socket)oResult.AsyncState; try { int nBytes = System.Convert.ToInt32(oSocket.EndReceive(oResult)); if (nBytes > 0) { string sData = (string)(System.Text.Encoding.ASCII.GetString(oString, 0, nBytes)); if (TCPDataArrivalEvent != null) { TCPDataArrivalEvent(sData); } f_WaitForData(oSocket); } else { oSocket.Shutdown(System.Net.Sockets.SocketShutdown.Both); oSocket.Close(); log.Info("Socket Closed"); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); log.Error("Error:" + ex.Message); } }
/// <summary> /// 域名注册信息 /// </summary> /// <param name="domain">输入域名,不包含www</param> /// <returns></returns> public static string GetDomain(string domain) { string strServer; string whoisServer = "whois.internic.net,whois.cnnic.net.cn,whois.publicinterestregistry.net,whois.nic.gov,whois.hkdnr.net.hk,whois.nic.name"; string[] whoisServerList = Regex.Split(whoisServer, ",", RegexOptions.IgnoreCase); if (domain == null) throw new ArgumentNullException(); int ccStart = domain.LastIndexOf("."); if (ccStart < 0 || ccStart == domain.Length) throw new ArgumentException(); //根据域名后缀选择服务器 string domainEnd = domain.Substring(ccStart + 1).ToLower(); switch (domainEnd) { default: //.COM, .NET, .EDU strServer = whoisServerList[0]; break; case "cn": //所有.cn的域名 strServer = whoisServerList[1]; break; case "org": //所有.org的域名 strServer = whoisServerList[2]; break; case "gov": //所有.gov的域名 strServer = whoisServerList[3]; break; case "hk": //所有.hk的域名 strServer = whoisServerList[4]; break; case "name": //所有.name的域名 strServer = whoisServerList[5]; break; } string ret = ""; Socket s = null; try { string cc = domain.Substring(ccStart + 1); s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.SendTimeout = 900; s.Connect(new IPEndPoint(Dns.Resolve(strServer).AddressList[0], 43)); s.Send(Encoding.ASCII.GetBytes(domain + "\r\n")); byte[] buffer = new byte[1024]; int recv = s.Receive(buffer); while (recv > 0) { ret += Encoding.UTF8.GetString(buffer, 0, recv); recv = s.Receive(buffer); } s.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { return ex.Message; } finally { if (s != null) s.Close(); } return ret; }
protected AbstractSocketChannel(IChannel parent, Socket socket) : base(parent) { Socket = socket; _state = StateFlags.Open; try { Socket.Blocking = false; } catch (SocketException ex) { try { socket.Close(); } catch (SocketException ex2) { if (Logger.IsWarningEnabled) { Logger.Warning("Failed to close a partially initialized socket.", ex2); } } throw new ChannelException("Failed to enter non-blocking mode.", ex); } }
public PolicyConnection(PolicyServer policyServer, Socket client, byte[] policy) { _policyServer = policyServer; _connection = client; _endpoint = _connection.RemoteEndPoint; _policy = policy; _buffer = new byte[_policyRequestString.Length]; _received = 0; try { // Receive the request from the client _connection.BeginReceive(_buffer, 0, _policyRequestString.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } catch (SocketException ex) { if (log.IsDebugEnabled) log.Debug("Socket exception", ex); _connection.Close(); } catch (Exception ex) { if (log.IsErrorEnabled) log.Error("Failed starting a policy connection", ex); } }
public static string SimpleSend(string input) { // Data buffer for incoming data. var bytes = new byte[1024]; input = $"{input}<EOF>"; // Connect to a remote device. // Establish the remote endpoint for the socket. var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, 6666); // Create a TCP/IP socket. var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. sender.Connect(remoteEndPoint); // Encode the data string into a byte array. var msg = Encoding.UTF8.GetBytes(input); // Send the data through the socket. var bytesSent = sender.Send(msg); // Receive the response from the remote device. var bytesRec = sender.Receive(bytes); var response = Encoding.UTF8.GetString(bytes, 0, bytesRec); // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); return response; }
/// <summary> /// NTP �T�[�o�[�A������w�肵�āA������擾���ă��[�J��������ݒ肷�� /// </summary> /// <param name="ntpServer">NTP �T�[�o�[</param> /// <param name="timezoneOffset">���� (�P�ʁF��)</param> /// <remarks>���<br /> /// http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c<br /> /// http://weblogs.asp.net/mschwarz/wrong-datetime-on-net-micro-framework-devices</remarks> public static void InitSystemTime(string ntpServer, int timezoneOffset) { var ep = new IPEndPoint(Dns.GetHostEntry(ntpServer).AddressList[0], 123); var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sock.Connect(ep); var ntpData = new byte[48]; ntpData[0] = 0x1b; for (var i = 1; i < 48; i++) ntpData[i] = 0; sock.Send(ntpData); sock.Receive(ntpData); sock.Close(); const int offset = 40; ulong intPart = 0; for (var i = 0; i <= 3; i++) intPart = 256 * intPart + ntpData[offset + i]; ulong fractPart = 0; for (var i = 4; i <= 7; i++) fractPart = 256 * fractPart + ntpData[offset + i]; var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L); var dateTime = new DateTime(1900, 1, 1).AddMilliseconds(milliseconds); var networkDateTime = dateTime + new TimeSpan(0, timezoneOffset, 0); Microsoft.SPOT.Hardware.Utility.SetLocalTime(networkDateTime); }
public static int DestorySocket(Socket socket) { int r = -1; try { //if (_socket.Connected) //{ // _socket.Disconnect(false); //} if (socket != null) { socket.Shutdown(SocketShutdown.Both); socket.DisconnectAsync(null); socket.Close(); socket.Dispose(); socket = null; } r = 0; } catch (Exception e) { Console.WriteLine(e.ToString()); r = -1; } return r; }
static void Main(string[] args) { IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddr = ipHost.AddressList[1]; List<int> freeSockets = new List<int>(); Parallel.For(0, 400, (i) => { IPEndPoint ipEnd = new IPEndPoint(ipAddr, i); Socket Listener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { Listener.Connect(ipEnd); freeSockets.Add(i); Console.WriteLine("Port {0} is free", i); } catch (Exception exc) { Console.WriteLine("Port {0} is busy", i); } finally { Listener.Close(); } } ); Console.WriteLine("\nFree sockets:"); Parallel.For(0, freeSockets.Count, (i) => { Console.WriteLine(freeSockets[i].ToString()); }); }
public bool CreateForward( IPEndPoint adbSockAddr, Device device, int localPort, int remotePort ) { Socket adbChan = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); try { adbChan.Connect ( adbSockAddr ); adbChan.Blocking = true; byte[] request = FormAdbRequest ( String.Format ( "host-serial:{0}:forward:tcp:{1};tcp:{2}", //$NON-NLS-1$ device.SerialNumber, localPort, remotePort ) ); if ( !Write ( adbChan, request ) ) { throw new IOException ( "failed to submit the forward command." ); } AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */); if ( !resp.IOSuccess || !resp.Okay ) { throw new IOException ( "Device rejected command: " + resp.Message ); } } finally { if ( adbChan != null ) { adbChan.Close ( ); } } return true; }
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)); }
//static void Main(string[] args, int a) public void send() { String name = Id.name; String a1 = "aantal schapen dood"; String a2 = link.a.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(); byte[] buffer = Encoding.Default.GetBytes(name); byte[] buffer1 = Encoding.Default.GetBytes(a1 + name); acc.Send(buffer, 0, buffer.Length, 0); acc.Send(buffer1, 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(); }
private static void ConnectAndTransfer() { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IPEndPoint ep = new IPEndPoint(hostIpAddr, portNo); socket.Connect(ep); Transfer(socket); socket.Close(); } }
/// <summary> /// 停止运行 /// </summary> public void Stop() { if (IsRun) { Interlocked.Decrement(ref isRun); } try { listen?.Close(); listen?.Shutdown(SocketShutdown.Both); } catch (Exception) { } listen = null; stopTime = DateTime.Now; ServerStopped?.Invoke(this, new EventArgs()); OnServerStopped(); }
// Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on // the specified host. public TcpClient(string hostname, int port) : this(AddressFamily.Unknown) { ArgumentNullException.ThrowIfNull(hostname); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, hostname); } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); } try { Connect(hostname, port); } catch { _clientSocket?.Close(); throw; } }
/// <summary> /// 停止端口监听。 /// </summary> public virtual void Stop() { serverSocket.Close(); IsStart = false; }
/// <summary> /// 客户端连接处理函数 /// </summary> /// <param name="iar">欲建立服务器连接的Socket对象</param> protected virtual void AcceptConn(IAsyncResult iar) { try { //如果服务器停止了服务,就不能再接收新的客户端 if (!this.ServerState) { return; } //接受一个客户端的连接请求 System.Net.Sockets.Socket oldserver = (System.Net.Sockets.Socket)iar.AsyncState; System.Net.Sockets.Socket client = oldserver.EndAccept(iar); //检查是否达到最大的允许的客户端数目 if (this.ClientCount >= this.DefaultMaxClient) { //服务器已满,发出通知 if (ServerFull != null) { ServerFull("服务连接数已满"); //继续接收来自来客户端的连接 sock.BeginAccept(new AsyncCallback(AcceptConn), sock); client.Close(); return; } } //添加到连接存储器中 Session s = new Session(client, ReceiveBufferSize); _SessionTable.Add(s.Id, s); if (ClientConn != null) { ClientConn(s); } try { //接着开始异步连接客户端 client.BeginReceive(s.ReceiveDataBuffer, 0, s.ReceiveDataBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveData), s); } catch (SocketException ex) { if (ServerError != null) { ServerError("Fail-EX:客户端连接;ErrorCode:" + ex.ErrorCode + ex.Message); } } catch (Exception ex) { if (ServerError != null) { ServerError("Fail-EX:客户端连接;" + ex.Message); } } //继续接收来自来客户端的连接 sock.BeginAccept(new AsyncCallback(AcceptConn), sock); } catch (Exception ex) { if (ServerError != null) { ServerError("Fail-EX:客户端连接;" + ex.Message); } } }
protected void OnBoopBtnClicked(object sender, EventArgs e) { //TODO: Check network connection try { //Fastest check first. if (!FilesToBoop.Any()) { //TODO: Throw error return; } if (NetUtils.Validate(targetIP.Text) == false) { //TODO: Throw error return; } string DSip = targetIP.Text; int ServerPort = Int32.Parse(Port.Text); // THE FIREWALL IS NO LONGER POKED! // THE SNEK IS FREE FROM THE HTTPLISTENER TIRANY! // setStatusLabel("Opening the new and improved snek server..."); // enableControls(false); Console.WriteLine("Active Dir"); Console.WriteLine(ActiveDir); Console.WriteLine("Port"); Console.WriteLine(ServerPort.ToString()); string SafeDir = ActiveDir + "/"; HTTPServer = new MyServer(ServerPort, ActiveDir); HTTPServer.Start(); System.Threading.Thread.Sleep(100); // setStatusLabel("Opening socket to send the file list..."); s = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = s.BeginConnect(DSip, 5000, null, null); result.AsyncWaitHandle.WaitOne(5000, true); if (!s.Connected) { s.Close(); HTTPServer.Stop(); // MessageBox.Show("Failed to connect to 3DS" + Environment.NewLine + "Please check:" + Environment.NewLine + "Did you write the right IP adress?" + Environment.NewLine + "Is FBI open and listening?", "Connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error); // lblIPMarker.Visible = true; // setStatusLabel("Ready"); // enableControls(true); return; } // setStatusLabel("Sending the file list..."); String message = ""; String formattedPort = ":" + Port.Text + "/"; foreach (var CIA in FilesToBoop) { message += NetUtils.GetLocalIPAddress() + formattedPort + System.Web.HttpUtility.UrlEncode(System.IO.Path.GetFileName(CIA)) + "\n"; } //boop the info to the 3ds... byte[] Largo = BitConverter.GetBytes((uint)Encoding.ASCII.GetBytes(message).Length); byte[] Adress = Encoding.ASCII.GetBytes(message); Array.Reverse(Largo); //Endian fix s.Send(AppendTwoByteArrays(Largo, Adress)); // setStatusLabel("Booping files... Please wait"); s.BeginReceive(new byte[1], 0, 1, 0, new AsyncCallback(GotData), null); //Call me back when the 3ds says something. //#if DEBUG } catch (Exception ex) { //Hopefully, some day we can have all the different exceptions handled... One can dream, right? *-* // MessageBox.Show("Something went really wrong: " + Environment.NewLine + Environment.NewLine + "\"" + ex.Message + "\"" + Environment.NewLine + Environment.NewLine + "If this keeps happening, please take a screenshot of this message and post it on our github." + Environment.NewLine + Environment.NewLine + "The program will close now", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Quit(); } //#endif }
public void Dispose() { exitFlag = true; server.Close(); }
/// <summary> /// 客户端消息分析 /// </summary> /// <param name="socket"></param> private static void AnalysisData(object socket) { try { Socket clientSocket = (Socket)socket; bool key = true; while (key) { byte[] buffer = new byte[BufferSize]; int bytes = clientSocket.Receive(buffer); if (bytes == 0) { continue; } try { string[] TempStrs = Encoding.Unicode.GetString(buffer, 0, bytes).Split('|'); string Command = ""; string Parameter1 = ""; string Parameter2 = ""; string Parameter3 = ""; string Parameter4 = ""; string Parameter5 = ""; string Parameter6 = ""; string Parameter7 = ""; string Parameter8 = ""; string Parameter9 = ""; //解析出命令字、命令参数 switch (TempStrs.Length) { case 1: Command = TempStrs[0]; break; case 2: Command = TempStrs[0]; Parameter1 = TempStrs[1]; break; case 3: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; break; case 4: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; break; case 5: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; Parameter4 = TempStrs[4]; break; case 6: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; Parameter4 = TempStrs[4]; Parameter5 = TempStrs[5]; break; case 7: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; Parameter4 = TempStrs[4]; Parameter5 = TempStrs[5]; Parameter6 = TempStrs[6]; break; case 8: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; Parameter4 = TempStrs[4]; Parameter5 = TempStrs[5]; Parameter6 = TempStrs[6]; Parameter7 = TempStrs[7]; break; case 9: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; Parameter4 = TempStrs[4]; Parameter5 = TempStrs[5]; Parameter6 = TempStrs[6]; Parameter7 = TempStrs[7]; Parameter8 = TempStrs[8]; break; case 10: Command = TempStrs[0]; Parameter1 = TempStrs[1]; Parameter2 = TempStrs[2]; Parameter3 = TempStrs[3]; Parameter4 = TempStrs[4]; Parameter5 = TempStrs[5]; Parameter6 = TempStrs[6]; Parameter7 = TempStrs[7]; Parameter8 = TempStrs[8]; Parameter9 = TempStrs[9]; break; } switch (Command) { case Command_C2S_Reg: switch (mainform.CheckLogName(Parameter1)) { case 0: mainform.AddClientList(Parameter1, ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString(), ((IPEndPoint)clientSocket.RemoteEndPoint).Port, DateTime.Now.ToString()); //返回登录成功 clientSocket.Send(Encoding.Unicode.GetBytes(RES_S2C_Reg + "|0|" + DateTime.Now.ToString() + "|" + Global.IsUseHongWai.ToString() + "|" + Global.IsTempVersion.ToString())); try { htusertick.Add(Parameter1, 0); //记录用户对应的socket htusersocket.Add(Parameter1, clientSocket); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } break; case 1: //返回登录失败:人数达到最大限额 clientSocket.Send(Encoding.Unicode.GetBytes(RES_S2C_Reg + "|1")); break; case 2: //返回登录失败:用户已经登录 object[] keyarray = new Object[htusersocket.Keys.Count]; Socket_Service.htusertick.Keys.CopyTo(keyarray, 0); string clientip = string.Empty; foreach (object obj in keyarray) { if (obj.ToString() == Parameter1) { Socket sc = (Socket)htusersocket[obj]; if (sc.Connected) //该账户的客户端连接正常 { IPEndPoint endpoint = (IPEndPoint)sc.RemoteEndPoint; clientip = endpoint.Address.ToString(); } else { clientip = "该账户连接正在断开请稍后"; } } } clientSocket.Send(Encoding.Unicode.GetBytes(RES_S2C_Reg + "|2" + "|" + clientip)); break; } break; case Command_C2S_ConnTick: //收到心跳消息则复位该用户心跳值为0 if (htusertick.Contains(Parameter1)) { htusertick[Parameter1] = 0; System.Net.Sockets.Socket tempsocket = (System.Net.Sockets.Socket)socket; System.Net.IPEndPoint tempendpoint = (System.Net.IPEndPoint)tempsocket.RemoteEndPoint; Console.WriteLine(tempendpoint.Address.ToString() + "--" + tempendpoint.Port.ToString() + "清0"); } Console.WriteLine("清0"); break; case Command_C2S_UnReg: key = false; mainform.RefreshClientList(ClientList); lock (htusersocket) { if (htusersocket.Contains(Parameter1)) { htusersocket.Remove(Parameter1); } } lock (htusertick) { if (htusertick.Contains(Parameter1)) { htusertick.Remove(Parameter1); } } break; case Command_C2S_AddRelation: int father = Convert.ToInt32(Parameter1); int son = Convert.ToInt32(Parameter2); //发送设置子基站命令 Socket_Service.mainform.hardChannel.Send(CommandFactory.GetAddSonCommand(father, son)); break; case Command_C2S_DelRelation: int fatherDelSon = Convert.ToInt32(Parameter1); int sonDelSon = Convert.ToInt32(Parameter2); //发送删除子基站命令 Socket_Service.mainform.hardChannel.Send(CommandFactory.GetDelSonCommand(fatherDelSon, sonDelSon)); break; case Command_C2S_DownMessage: int cardID = Convert.ToInt32(Parameter1); int messageType = Convert.ToInt32(Parameter2); //根据连接方式发送短信 if (mainform.hardChannel.GetType() == Type.GetType("PersonPositionServer.Model.TcpSocket_Service")) { //网口:给所有网关基站一个一个的发 System.Data.DataRow[] rows = BasicData.GetStationTableRows("StationType = '网关基站'", true); for (int i = 0; i < rows.Length; i++) { try { int stationID = Convert.ToInt32(rows[i]["ID"]); Socket_Service.mainform.hardChannel.Send(CommandFactory.GetDownMessageCommand(stationID, cardID, messageType)); } catch (Exception ex) { if (Global.IsShowBug) { System.Windows.Forms.MessageBox.Show(ex.Message + "\n" + ex.TargetSite + "\n" + ex.StackTrace, "服务器下发短信错误"); } } } } else { //串口:给Can总线群发 Socket_Service.mainform.hardChannel.Send(CommandFactory.GetDownMessageCommand(1023, cardID, messageType)); //这里的1023是0x:03FF 是Can总线中的广播地址 } break; case Command_C2S_RequestDownMesType: //给客户端发送下行短信类型 clientSocket.Send(Encoding.Unicode.GetBytes(Command_S2C_DownMesType + "|" + Global.DownM0 + "=" + Global.DownM1 + "=" + Global.DownM2 + "=" + Global.DownM3 + "=" + Global.DownM4 + "=" + Global.DownM5 + "=" + Global.DownM6 + "=" + Global.DownM7 + "=" + Global.DownM8 + "=" + Global.DownM9 + "=" + Global.DownM10 + "=" + Global.DownM11)); break; case Command_C2S_RequestInArea: //给客户端发送特殊区域内人员 clientSocket.Send(Encoding.Unicode.GetBytes(Command_S2C_InArea + "|" + Protocol_Service.InArea.Count.ToString() + "|" + Protocol_Service.GetPresentInAreaStr())); break; case Command_C2S_LightUp: //发送点亮灯命令 if (Socket_Service.mainform.hardChannel.Send_Safe(Protocol_Service.CommandType.LightUp, CommandFactory.GetLightUpCommand(Convert.ToInt32(Parameter1), Convert.ToInt32(Parameter2)))) { //返回点亮灯成功 clientSocket.Send(Encoding.Unicode.GetBytes(RES_S2C_LightUp)); } break; case Command_C2S_HandCheckOut: //强制离开指定的员工 if (Protocol_Service.HandCheckOut(Convert.ToInt32(Parameter1))) { //返回强制离开成功 clientSocket.Send(Encoding.Unicode.GetBytes(RES_S2C_HandCheckOut)); } break; case Command_C2S_UpdateDB: Dictionary <string, string> ParameterList = new Dictionary <string, string>(); ParameterList.Add(Parameter1, Parameter1); if (Parameter2 != "") { ParameterList.Add(Parameter2, Parameter2); if (Parameter3 != "") { ParameterList.Add(Parameter3, Parameter3); if (Parameter4 != "") { ParameterList.Add(Parameter4, Parameter4); if (Parameter5 != "") { ParameterList.Add(Parameter5, Parameter5); if (Parameter6 != "") { ParameterList.Add(Parameter6, Parameter6); if (Parameter7 != "") { ParameterList.Add(Parameter7, Parameter7); if (Parameter8 != "") { ParameterList.Add(Parameter8, Parameter8); if (Parameter9 != "") { ParameterList.Add(Parameter9, Parameter9); } } } } } } } } if (ParameterList.ContainsKey("CardTable")) { BasicData.RefreshCardTable(); } if (ParameterList.ContainsKey("CollectChannelTable")) { BasicData.RefreshCollectChannelTable(); } if (ParameterList.ContainsKey("PersonTable")) { BasicData.RefreshPersonTable(); } if (ParameterList.ContainsKey("SpecalTable")) { BasicData.RefreshSpecalTable(); } if (ParameterList.ContainsKey("StationTable")) { BasicData.RefreshStationTable(); } //给除这个客户端以外的所有客户端发送数据库更新消息 BroadcastMessageWithOutOne(clientSocket, Socket_Service.Command_S2C_UpdateDB, Parameter1, Parameter2, Parameter3, Parameter4, Parameter5, Parameter6, Parameter7, Parameter8, Parameter9); break; case Command_C2S_AreaSubject: //返回命令成功 clientSocket.Send(Encoding.Unicode.GetBytes(RES_S2C_AreaSubject)); switch (Parameter1) { case "ON": Protocol_Service.AlarmAreaName = Parameter2; break; case "OFF": Protocol_Service.AlarmAreaName = "未启动"; Protocol_Service.InArea.Clear(); Protocol_Service.IsExceedInArea = false; break; case "CHANGE": Protocol_Service.AlarmAreaName = Parameter2; break; } break; case Command_C2S_SetInfo: Socket_Service.mainform.hardChannel.Send(CommandFactory.GetSetInfoCommand(Convert.ToInt32(Parameter1), Convert.ToByte(Parameter2), Convert.ToByte(Parameter3), Parameter4)); break; } } catch (Exception ex) { if (Global.IsShowBug) { System.Windows.Forms.MessageBox.Show(ex.Message + "\n" + ex.TargetSite + "\n" + ex.StackTrace, "服务器解析客户端命令错误"); } //在解析命令时如果有错,则忽略 } } ClientList.Remove(socket); clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); mainform.RefreshClientList(ClientList); } catch { ClientList.Remove(socket); //在htlcientsock和htusertick中清除该socket object[] keyarray = new Object[htusersocket.Keys.Count]; Socket_Service.htusertick.Keys.CopyTo(keyarray, 0); System.Net.Sockets.Socket csocket = (System.Net.Sockets.Socket)socket; if (csocket.Connected && csocket != null)//远程主机未强制关闭 { System.Net.IPEndPoint cendpoint = (System.Net.IPEndPoint)csocket.RemoteEndPoint; foreach (object obj in keyarray) { System.Net.Sockets.Socket htsocket = (System.Net.Sockets.Socket)htusersocket[obj]; System.Net.IPEndPoint htendPoint = (System.Net.IPEndPoint)htsocket.RemoteEndPoint; if ((htendPoint.Address.ToString() == cendpoint.Address.ToString()) && (htendPoint.Port == cendpoint.Port)) { //先关闭连接再移除 htsocket.Shutdown(SocketShutdown.Both); htsocket.Close(); htusersocket.Remove(obj); htusertick.Remove(obj); } } } else//远程主机已强制关闭 { foreach (object obj in keyarray) { System.Net.Sockets.Socket htsocket = (System.Net.Sockets.Socket)htusersocket[obj]; if (!htsocket.Connected && htsocket != null) { htsocket.Shutdown(SocketShutdown.Both); htsocket.Close(); htusersocket.Remove(obj); htusertick.Remove(obj); } } } mainform.RefreshClientList(ClientList); } }
public void close() { //s.Shutdown(SocketShutdown.Send); s.Close(); }
void Utils.Wrappers.Interfaces.ISocket.Close() { InternalSocket.Close(); }
public async Task <SocketStream> ConnectAsync() { _socket = await NaiveUtils.ConnectTcpAsync(new AddrPort(_socksAddr, _socksPort), 0); var _ns = MyStream.FromSocket(_socket); var user = _username; var pass = _password ?? ""; byte[] buffer = user == null ? new byte[] { SOCKS_VER, 1, NOAUTH } : new byte[] { SOCKS_VER, AUTH_METH_SUPPORT, NOAUTH, USER_PASS_AUTH }; await _ns.WriteAsyncR(buffer); await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, 2)); if (buffer[1] == NOAUTH) { // nothing to do. } else if (buffer[1] == USER_PASS_AUTH) { byte[] credentials = new byte[user.Length + pass.Length + 3]; var pos = 0; credentials[pos++] = 1; credentials[pos++] = (byte)user.Length; pos += Encoding.ASCII.GetBytes(user, 0, user.Length, credentials, pos); credentials[pos++] = (byte)pass.Length; pos += Encoding.ASCII.GetBytes(pass, 0, pass.Length, credentials, pos); await _ns.WriteAsyncR(credentials); await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, 2)); if (buffer[1] != SOCKS_CMD_SUCCSESS) { throw new SocksRefuseException("Invalid username or password."); } } else { _socket.Close(); throw new SocksAuthException(); } byte addrType = GetAddressType(); byte[] address = GetDestAddressBytes(addrType, _destAddr); byte[] port = GetDestPortBytes(_destPort); buffer = new byte[4 + port.Length + address.Length]; buffer[0] = SOCKS_VER; buffer[1] = CMD_CONNECT; buffer[2] = 0x00; //reserved buffer[3] = addrType; address.CopyTo(buffer, 4); port.CopyTo(buffer, 4 + address.Length); await _ns.WriteAsyncR(buffer); buffer = new byte[256]; await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, 4)); if (buffer[1] != SOCKS_CMD_SUCCSESS) { throw new SocksRefuseException($"remote socks5 server returns {new BytesView(buffer, 0, 4)}"); } switch (buffer[3]) { case 1: await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, 4 + 2)); break; case 3: await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, 1)); await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, buffer[0])); break; case 4: await _ns.ReadFullAsyncR(new BytesSegment(buffer, 0, 16 + 2)); break; default: throw new Exception("Not supported addr type: " + buffer[3]); } return(_ns); }
protected void p2psev_EventUpdataConnSoc(System.Net.Sockets.Socket soc) { ConnObj cobj = new ConnObj(); try { cobj.Soc = soc; IPEndPoint clientipe = (IPEndPoint)soc.RemoteEndPoint; counttemp++; //这里通过IP和PORT获取对象 cobj.Token = clientipe.Address.ToString() + ":" + clientipe.Port;// EncryptDES(clientipe.Address.ToString() + "|" + DateTime.Now.ToString(), "lllssscc"); cobj.Soc = soc; if (counttemp > max) { int mincount = int.MaxValue; string tempip = ""; foreach (WayItem ci in WayItemS) { if (ci.Num < mincount) { mincount = ci.Num; tempip = ci.Ip + ":" + ci.Port; } } if (Wptype == WeavePortTypeEnum.Bytes) { p2psev.Send(soc, 0xff, UTF8Encoding.UTF8.GetBytes("jump|" + tempip + "")); } else { p2psev.Send(soc, 0xff, "jump|" + tempip + ""); } soc.Close(); return; } //IPEndPoint clientipe = (IPEndPoint)soc.RemoteEndPoint; if (Wptype != WeavePortTypeEnum.Bytes) { p2psev.Send(soc, 0xff, "token|" + cobj.Token + ""); } GateHelper.SetConnItemlist(ConnItemlist, cobj, Pipeline); List <String> listsercer = new List <string>(); bool tempb = true; foreach (CommandItem ci in CommandItemS) { tempb = true; foreach (string ser in listsercer) { if (ser == (ci.Ip + ci.Port)) { tempb = false; goto lab882; } } lab882: if (tempb) { if (ci.Client4_10[0, 0, 0, 0] != null) { listsercer.Add(ci.Ip + ci.Port); ci.Client4_10[0, 0, 0, Convert.ToInt32(clientipe.Port.ToString().Substring(clientipe.Port.ToString().Length - 1, 1))].send(0xff, "in|" + cobj.Token); } } } } catch (Exception ex) { if (EventMylog != null) { EventMylog("EventUpdataConnSoc", ex.Message); } } }
/// <summary> /// Processes incoming requests /// </summary> protected void ProcessRequest() { // accept an incoming connection request and once we have one, spawn a new thread to accept more bool newThread = false; System.Net.Sockets.Socket clientSocket = null; Responder responder = null; while (IsRunning && !newThread) { try { // process incoming request clientSocket = LocalServer.Accept(); clientSocket.ReceiveTimeout = Timeout; clientSocket.SendTimeout = Timeout; // parse message an create an object containing parsed data responder = new Responder(); responder.ClientEndpoint = clientSocket.RemoteEndPoint.ToString(); responder.ClientSocket = clientSocket; Thread t = new Thread(new ThreadStart(ProcessRequest)); t.Start(); newThread = true; } catch { if (clientSocket != null) { try { clientSocket.Close(); } catch { } } } } // now process the request try { bool finishedParsing = false; TimeSpan parseStart = Timer.GetMachineTime(); while (!finishedParsing) { if (Timer.GetMachineTime() - parseStart > MaxProcessingTime) { return; } // receiving data, add to an array to process later byte[] buffer = new byte[clientSocket.Available]; clientSocket.Receive(buffer); finishedParsing = responder.parse(buffer); } // trigger event to get response WebEvent webevent = null; if (responder.Path != null && responder.Path.Length > 1) { webevent = serverManager.GetWebEventById(responder.Path); } if (webevent == null) { webevent = serverManager.DefaultEvent; } responder.webEvent = webevent; webevent.OnWebEventReceived(responder.Path, responder.HttpMethod, responder); } catch { } }
private void processRequest() { // 設定接收資料緩衝區 byte[] bytes = new byte[1024]; string htmlRequest = ""; try { // 自已連線的用戶端接收資料 int bytesReceived = clientSocket.Receive(bytes, 0, bytes.Length, SocketFlags.None); htmlRequest = Encoding.ASCII.GetString(bytes, 0, bytesReceived); Console.WriteLine("HTTP Request: \r\n" + htmlRequest); // 指定專案所在目錄為網站的主目錄 string rootPath = Directory.GetCurrentDirectory() + "\\WWWRoot\\"; // Set default page string defaultPage = "index.html"; string[] buffer; string request; buffer = htmlRequest.Trim().Split(" ".ToCharArray()); // Determine the HTTP method (GET only) if (buffer[0].Trim().ToUpper().Equals("GET")) { request = buffer[1].Trim().ToString(); if (request.StartsWith("/")) { request = request.Substring(1); } if (request.EndsWith("/") || request.Equals("")) { request = request + defaultPage; } request = rootPath + request; sendHTMLResponse(request); } else // HTTP GET method not available { request = rootPath + "Error\\" + "400.html"; sendHTMLResponse(request); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.StackTrace.ToString()); if (clientSocket.Connected) { clientSocket.Close(); } } }
public void Stop() { _listenerSocket.Close(); _listenerSocket.Dispose(); }
public void Exit() { _clientSocket.Shutdown(SocketShutdown.Both); _clientSocket.Close(); }
protected override void Free(bool canAccessFinalizable) { if (FWriteQueue != null) { FWriteQueue.Clear(); FWriteQueue = null; } if (FStream != null) { FStream.Close(); FStream = null; } if (FDecryptor != null) { FDecryptor.Dispose(); FDecryptor = null; } if (FEncryptor != null) { FEncryptor.Dispose(); FEncryptor = null; } if (FReadOV != null) { Type t = typeof(SocketAsyncEventArgs); FieldInfo f = t.GetField("m_Completed", BindingFlags.Instance | BindingFlags.NonPublic); f.SetValue(FReadOV, null); FReadOV.SetBuffer(null, 0, 0); FReadOV.Dispose(); FReadOV = null; } if (FWriteOV != null) { Type t = typeof(SocketAsyncEventArgs); FieldInfo f = t.GetField("m_Completed", BindingFlags.Instance | BindingFlags.NonPublic); f.SetValue(FWriteOV, null); FWriteOV.SetBuffer(null, 0, 0); FWriteOV.Dispose(); FWriteOV = null; } if (FSocket != null) { FSocket.Close(); FSocket = null; } FHost = null; FCreator = null; FSyncReadPending = null; FSyncData = null; FSyncEventProcessing = null; base.Free(canAccessFinalizable); }
public void ShutdownAndClose() { m_socket.Shutdown(SocketShutdown.Both); m_socket.Close(); }
/// <summary> /// 关闭 <see cref="Socket"/> 连接并释放所有关联的资源 /// </summary> public void Close() { _socket.Close(); }
IEnumerator RestoreUpdate() { if (Application.internetReachability == NetworkReachability.NotReachable) { Log.LogInfo("connect time out"); MainLoader.ChangeStep(LoadStep.NotNeedUpdate); yield break; } else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork) { //3G Tip } //Restore DownLoad From Progress.xml System.Net.Sockets.Socket sClient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); System.Net.EndPoint server = new System.Net.IPEndPoint(Dns.GetHostAddresses(GameData.Domain)[0], System.Convert.ToInt32(strPort)); System.Threading.ManualResetEvent connectDone = new System.Threading.ManualResetEvent(false); try { connectDone.Reset(); sClient.BeginConnect(server, delegate(IAsyncResult ar) { try { System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState; client.EndConnect(ar); } catch (System.Exception e) { Log.LogInfo(e.Message + "|" + e.StackTrace); } finally { connectDone.Set(); } } , sClient); //timeout if (!connectDone.WaitOne(2000)) { Log.LogInfo("connect time out"); MainLoader.ChangeStep(LoadStep.CannotConnect); yield break; } else { if (!sClient.Connected) { Log.LogInfo("connect disabled by server"); MainLoader.ChangeStep(LoadStep.CannotConnect); yield break; } } } catch { sClient.Close(); MainLoader.ChangeStep(LoadStep.CannotConnect); yield break; } finally { connectDone.Close(); } //Log.LogInfo("download:" + string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName)); using (WWW vFile = new WWW(string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName))) { //Log.LogInfo("error:" + vFile.error); yield return(vFile); if (vFile.error != null && vFile.error.Length != 0) { //Log.LogInfo("error " + vFile.error); vFile.Dispose(); //not have new version file //can continue game MainLoader.ChangeStep(LoadStep.NotNeedUpdate); yield break; } if (vFile.bytes != null && vFile.bytes.Length != 0) { File.WriteAllBytes(strUpdatePath + "/" + "v.zip", vFile.bytes); DeCompressFile(strUpdatePath + "/" + "v.zip", strUpdatePath + "/" + "v.xml"); vFile.Dispose(); } else { MainLoader.ChangeStep(LoadStep.NotNeedUpdate); yield break; } } XmlDocument xmlVer = new XmlDocument(); xmlVer.Load(strUpdatePath + "/" + "v.xml"); XmlElement ServerVer = xmlVer.DocumentElement; if (ServerVer != null) { string strServer = ServerVer.GetAttribute("ServerV"); UpdateClient = HttpManager.AllocClient(string.Format(strDirectoryBase, strHost, strPort, strProjectUrl, strPlatform, strServer, "")); //if (strServer != null && GameData.Version().CompareTo(strServer) == -1) //{ // strServerVer = strServer; // foreach (XmlElement item in ServerVer) // { // string strClientV = item.GetAttribute("ClientV"); // if (strClientV == GameData.Version()) // { // strUpdateFile = item.GetAttribute("File"); // break; // } // } // if (strUpdateFile != null && strUpdateFile.Length != 0) // StartCoroutine("DownloadNecessaryData"); //} //else //{ // Log.LogInfo("not need update"); // MainLoader.ChangeStep(LoadStep.NotNeedUpdate); //} } }
public void ConnectDeviceThread() { string ip = ""; lock (this)//拿出一个IP { foreach (var IP in DeviceIP) { if (IP.Value.Length == 0) { ip = IP.Key; break; } } DeviceIP[ip] = "Connecting"; } bool TimeOut = false; //超时标志 bool Connected = false; //已经连接上标志 string Resourt = ""; IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), 8086); //把ip和端口转化为IPEndpoint实例 //创建socket并连接到服务器 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建Socket ManualResetEvent TimeoutObject = new ManualResetEvent(false); TimeoutObject.Reset(); c.BeginConnect(ipe, asyncResult => //开始链接 { //链接完毕后 try { if (TimeOut)//如果超时了才进入 则立刻退出 { throw new System.Exception("Connect time out"); } c.EndConnect(asyncResult); if (c.Connected) { //向服务器发送信息 Log.Info("tcp:" + ip, "Send message start"); string sendStr = "AreYouThere"; byte[] bs = Encoding.ASCII.GetBytes(sendStr); //把字符串编码为字节 c.Send(bs, bs.Length, 0); //发送信息 Log.Info("tcp:" + ip, "Send message complete"); ///接受从服务器返回的信息 string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; try { c.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 600); bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); } catch //接收确认信息超时 立刻退出 { throw new System.Exception("ReceiveTimeOut"); } Resourt = recvStr; Log.Info("tcp:" + ip, "Get essage:" + recvStr); //显示服务器返回信息 if (recvStr.Contains("AAA")) //获得了正确的确认信息 { Connected = true; lock (this) { Device device = new Device();//加入这个设备 device.DevIp = ip; device.DevSocket = c; Devices.Add(device); } new Java.Lang.Thread(ConmmunityDeviceThread).Start();//启动一个与当前设备通信的进程 } } else//没链接上时 立刻退出 { throw new System.Exception("No connect"); } } catch (System.Exception e) { Log.Error("tcp:" + ip, e.Message);//显示服务器返回信息 Resourt = e.Message; } finally { lock (this) { DeviceIP[ip] = Resourt; } //使阻塞的线程继续 TimeoutObject.Set(); } }, c); //阻塞当前线程 if (!TimeoutObject.WaitOne(700, false)) { //链接超时 if (Connected == false) //未连接上 { Log.Error("tcp:" + ip, "Time out"); //显示服务器返回信息 TimeOut = true; c.Close(); } } if (TheardComplete++ >= ConnectDeviceTheardNum) { TheardComplete = 0; //清空完成线程数 FLAG_Scaning = false; //关闭扫描中标志 可以开启下一次扫描 } }
//private void connectTimeoutTimerDelegate(Object stateInfo) //{ // // for compression debug statisticsConsole.WriteLine("Connect Timeout"); // connectTimeoutTimer.Dispose(); // m_ConnectTimedOut = true; // //_socket.Close(); //} //private void EndConnect(IAsyncResult ar) //{ // if (m_ConnectTimedOut) // { // FireOnError("Attempt to connect timed out"); // } // else // { // if (OnConnected != null) // OnConnected.Invoke(); // Receive(); // } //} private void asyncConnectAndSend() { try { bError = false; bDisconnect = false; sendList = new List <byte[]>(); socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = true; var address = IPAddress.Parse(ip); IPEndPoint endPoint = new IPEndPoint(address, port); socket.Connect(endPoint); reader = new TcpSocketReader(socket); if (OnConnected != null) { OnConnected.Invoke(); } Thread recvThread = new Thread(asyncReceive); recvThread.IsBackground = true; recvThread.Start(); List <byte[]> list = new List <byte[]>(); List <byte> tmp = new List <byte>(); //send loop while (true) { if (bDisconnect) { break; } lock (sendList) { if (sendList.Count > 0) { int bufflen = 0; for (int i = 0; i < sendList.Count; i++) { if (bufflen + sendList[i].Length > 8192) { if (tmp.Count > 0) { list.Add(tmp.ToArray()); tmp.Clear(); } list.Add(sendList[i]); bufflen = 0; } else { bufflen += sendList[i].Length; tmp.AddRange(sendList[i]); } //list.AddRange(sendList[i]); } if (tmp.Count > 0) { list.Add(tmp.ToArray()); tmp.Clear(); } sendList.Clear(); } } if (list.Count > 0) { for (int i = 0; i < list.Count; i++) { socket.Send(list[i], SocketFlags.None); } //var buff = list.ToArray(); //socket.Send(buff, SocketFlags.None); list.Clear(); } else { Thread.Sleep(10); } } if (bError) { socket.Close(); } else { socket.Close(); if (OnClosed != null) { OnClosed.Invoke(); } } } catch (Exception ex) { if (!bError) { fireOnError(ex.ToString()); } socket.Close(); } }
public void close() { sock.Close(); }
public static void Main(System.String[] args) { int port = 8888; // System.String server = "localhost"; System.String server = "13.125.250.235"; System.Net.Sockets.Socket socket = null; System.String lineToBeSent; System.IO.StreamReader input; System.IO.StreamWriter output; int ERROR = 1; // read arguments if (args.Length == 2) { server = args[0]; try { port = System.Int32.Parse(args[1]); } catch (System.Exception e) { System.Console.Out.WriteLine("server port = 8888 (default)"); port = 8888; } } // connect to server try { //UPGRADE_ISSUE: Method 'java.net.Socket.getInetAddress' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javanetSocketgetInetAddress"' //UPGRADE_ISSUE: Method 'java.net.Socket.getPort' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javanetSocketgetPort"' //System.Console.Out.WriteLine("Connected with server " + socket.getInetAddress() + ":" + socket.getPort()); } catch (System.Exception e) { System.Console.Out.WriteLine(e); System.Environment.Exit(ERROR); } try { //UPGRADE_TODO: Expected value of parameters of constructor 'java.io.BufferedReader.BufferedReader' are different in the equivalent in .NET. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092"' //UPGRADE_ISSUE: 'java.lang.System.in' was converted to 'System.Console.In' which is not valid in this expression. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1109"' // input = new System.IO.StreamReader(new System.IO.StreamReader(System.Console.In).BaseStream, System.Text.Encoding.UTF7); // System.IO.StreamWriter temp_writer; // temp_writer = new System.IO.StreamWriter((System.IO.Stream) socket.GetStream()); // temp_writer.AutoFlush = true; // output = temp_writer; // get user input and transmit it to server System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("13.125.250.235"); System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd, 8888); socket.Connect(remoteEP); //Async Read form the server side Receive(socket); //new System.Net.Sockets.TcpClient(server, port); while (true) { lineToBeSent = System.Console.ReadLine(); // stop if input line is "." if (lineToBeSent.Equals(".")) { socket.Close(); break; } //output.WriteLine(lineToBeSent);\ //System.Net.Sockets.NetworkStream tempstream = socket.GetStream(); socket.Send(encoding.GetBytes(lineToBeSent)); } //socket.Close(); byte[] Serbyte = new byte[30]; // socket.Receive(Serbyte,0,20,System.Net.Sockets.SocketFlags.None); // System.Console.WriteLine("Message from server \n" + encoding.GetString(Serbyte)); //socket.Close(); } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e); } try { } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e); } }
void ISocket.Close() { m_Sender.Stop(); m_Socket.Close(); }
//dong ket noi hien thoi. void close() { server.Close(); }
private void Connect(HttpWebRequest request) { object obj = this.socketLock; lock (obj) { if (this.socket != null && this.socket.Connected && this.status == WebExceptionStatus.Success && this.CanReuse() && this.CompleteChunkedRead()) { this.reused = true; } else { this.reused = false; if (this.socket != null) { this.socket.Close(); this.socket = null; } this.chunkStream = null; IPHostEntry hostEntry = this.sPoint.HostEntry; if (hostEntry == null) { this.status = ((!this.sPoint.UsesProxy) ? WebExceptionStatus.NameResolutionFailure : WebExceptionStatus.ProxyNameResolutionFailure); } else { WebConnectionData data = this.Data; foreach (IPAddress ipaddress in hostEntry.AddressList) { this.socket = new System.Net.Sockets.Socket(ipaddress.AddressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); IPEndPoint ipendPoint = new IPEndPoint(ipaddress, this.sPoint.Address.Port); this.socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.Debug, (!this.sPoint.UseNagleAlgorithm) ? 1 : 0); this.socket.NoDelay = !this.sPoint.UseNagleAlgorithm; if (!this.sPoint.CallEndPointDelegate(this.socket, ipendPoint)) { this.socket.Close(); this.socket = null; this.status = WebExceptionStatus.ConnectFailure; } else { try { if (request.Aborted) { break; } this.CheckUnityWebSecurity(request); this.socket.Connect(ipendPoint, false); this.status = WebExceptionStatus.Success; break; } catch (ThreadAbortException) { System.Net.Sockets.Socket socket = this.socket; this.socket = null; if (socket != null) { socket.Close(); } break; } catch (ObjectDisposedException ex) { break; } catch (Exception ex2) { System.Net.Sockets.Socket socket2 = this.socket; this.socket = null; if (socket2 != null) { socket2.Close(); } if (!request.Aborted) { this.status = WebExceptionStatus.ConnectFailure; } this.connect_exception = ex2; } } } } } } }
public void Shutdown() { ListenSocket.Close(); }
private void btnStart_Click(object sender, EventArgs e) { if (cmbInterfaces.Text == "") { MessageBox.Show("请选择一个网卡接口进行抓包!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); cmbInterfaces.Focus(); return; } try { _AssumeMaskAddress = System.Text.RegularExpressions.Regex.Replace(cmbInterfaces.Text, "\\.(\\d{1,3})$", ".255"); if (!bContinueCapturing) { //Start capturing the packets... btnStart.Text = "暂停(&S)"; bContinueCapturing = true; //For sniffing the socket to capture the packets has to be a raw socket, with the //address family being of type internetwork, and protocol being IP mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); //Bind the socket to the selected IP address mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 0)); //Set the socket options mainSocket.SetSocketOption(SocketOptionLevel.IP, //Applies only to IP packets SocketOptionName.HeaderIncluded, //Set the include the header true); //option to true byte[] incoming = new byte[4] { 1, 0, 0, 0 }; byte[] outgoing = new byte[4] { 1, 0, 0, 0 }; //Socket.IOControl is analogous to the WSAIoctl method of Winsock 2 mainSocket.IOControl(IOControlCode.ReceiveAll, //Equivalent to SIO_RCVALL constant of Winsock 2 incoming, outgoing); //Start receiving the packets asynchronously mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), mainSocket); } else { btnStart.Text = "抓包(&S)"; bContinueCapturing = false; //To stop capturing the packets close the socket if (mainSocket != null) { mainSocket.Close(); } } } catch (Exception ex) { if (ex is SocketException) { SocketException sEx = (SocketException)ex; if (sEx.SocketErrorCode == SocketError.AccessDenied) { MessageBox.Show("权限不足:请以管理员方式运行本程序!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }