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(); }
internal void NegotiationsFinishedFireConnected(bool bSuccess, string strErrors) { if (bSuccess == false) { if (m_Logger != null) { m_Logger.LogError(ToString(), MessageImportance.Medium, "Failed TLS negotiation"); } try { Client.Shutdown(System.Net.Sockets.SocketShutdown.Both); } catch (Exception) { } } if (m_Logger != null) { m_Logger.LogMessage(ToString(), MessageImportance.Medium, "Connected"); } OnConnected(bSuccess, strErrors); if (OnAsyncConnectFinished != null) { OnAsyncConnectFinished(this, true, ""); } if ((m_bStartReadOnConnect) && (this.Connected == true)) { DoAsyncRead(); } }
private byte[] ClientCreateSendAndReceive(byte[] dataToSend) { var bufferSize = 512; var buffer = new byte[bufferSize]; var socket = new Socket(_serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(_serverAddress); socket.Send(dataToSend); socket.Shutdown(SocketShutdown.Send); using (var memory = new MemoryStream(bufferSize)) { int bytesRec; while ((bytesRec = socket.Receive(buffer)) > 0) { memory.Write(buffer, 0, bytesRec); } socket.Shutdown(SocketShutdown.Receive); socket.Close(); buffer = memory.ToArray(); } return buffer; }
private Socket SOCKET; //receive socket #endregion Fields #region Methods public void Begin() { connect: SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404); Console.WriteLine("S104 establish a link successfully, try to receive..."); RCV_THREAD = new System.Threading.Thread(BeginReceive); RCV_THREAD.Start(SOCKET); while (true) { System.Threading.Thread.Sleep(4000); this.Send_UFram(Uflag.testfr_active); if (RCVD_NUM >= 20000) { SOCKET.Shutdown(SocketShutdown.Receive); RCV_THREAD.Abort(); System.Threading.Thread.Sleep(4000); SOCKET.Shutdown(SocketShutdown.Send); SOCKET.Dispose(); RCVD_NUM = 0; goto connect; } if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4)) { this.Send_SFram(RCVD_NUM); Console.WriteLine("overtime send S fram..."); } } }
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()); } }
public static void ShutdownSocket(Socket socket) { if (socket == null) return; Helper.EatException(() => socket.Shutdown(SocketShutdown.Both)); Helper.EatException(() => socket.Close(10000)); }
public void SendMessage(Packet clientPacket) { byte[] result = new byte[1024]; //设定服务器IP地址 IPAddress ip = IPAddress.Parse("192.168.0.22"); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(new IPEndPoint(ip, 11111)); //配置服务器IP与端口 Console.WriteLine("连接服务器成功"); } catch { Console.WriteLine("连接服务器失败,请按回车键退出!"); return; } //通过clientSocket接收数据 int receiveLength = clientSocket.Receive(result); Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength)); //通过 clientSocket 发送数据 try { //string sendMessage = "client send Message Hellp" + DateTime.Now; //clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage)); clientSocket.Send(clientPacket.DoGetPacketBytes()); //Console.WriteLine("向服务器发送消息:{0}" + sendMessage); } catch { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } }
public bool disconnect(Socket soc) { // Release the socket. soc.Shutdown(SocketShutdown.Both); soc.Close(); return true; }
private void SendQuery2(IPAddress ipAddress, int port) { int timeout = 5000; if (ipAddress == null) { throw new ArgumentNullException(); } //preparing the DNS query packet. byte[] QueryPacket = MakeQuery(); //opening the UDP socket at DNS server IPAddress serverAddress = ipAddress; EndPoint endPoint = new IPEndPoint(serverAddress, port); SOCKET socket = new SOCKET(serverAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout); socket.SendTo(QueryPacket, endPoint); data = new byte[512]; length = socket.ReceiveFrom(data, ref endPoint); //un pack the byte array & makes an array of resource record objects. ReadResponse(); socket.Shutdown(SocketShutdown.Both); }
static void Main(string[] args) { var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Console.Out.WriteLine("Connecting to server..."); sock.Connect(endpoint); Console.Out.WriteLine("Connected!"); var rnd = new Random(); int packetCount = rnd.Next(0, 2000); for (int i = 0; i < packetCount; i++) { Console.Out.WriteLine("Generating random test data"); var packet = CreateRandomPacket(rnd); Console.Out.WriteLine("Sending data to server..."); if (rnd.Next(0, 1) == 0) { SendWhole(sock, packet); } else { SendPartial(sock, packet); } Thread.Sleep(rnd.Next(100, 1000)); } Console.Out.WriteLine("Shutting down..."); sock.Shutdown(SocketShutdown.Both); sock.Close(); }
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(); } }
static void Main(string[] args) { byte[] buffer = new byte[1024]; // Idea terrible usar SaveFileDialog en una aplicación de consola // Hecho solo con propósitos educativos: using (OpenFileDialog fileDialog = new OpenFileDialog()) { fileDialog.Multiselect = true; if (fileDialog.ShowDialog() == DialogResult.OK) { IPEndPoint remotePoint = new IPEndPoint(IPAddress.Loopback, 4040); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(remotePoint); FileWriter sw = new FileWriter(s); sw.WriteInt32(fileDialog.FileNames.Count()); for (int i = 0; i < fileDialog.FileNames.Count(); i++) { sw.WriteString(Path.GetFileName(fileDialog.FileNames[i])); sw.WriteFile(fileDialog.FileNames[i]); } s.Shutdown(SocketShutdown.Both); s.Close(); } Console.Read(); } }
static void Main(string[] args) { IPAddress addr = IPAddress.Parse("127.0.0.1"); Socket client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client.Connect(new IPEndPoint(addr, 5555)); // connect success } catch { // connect failed client.Shutdown(SocketShutdown.Both); client.Close(); return; } bool running = true; Thread t = new Thread(() => { byte[] recv_buffer = new byte[1024]; while (running) { int recv_length = client.Receive(recv_buffer); // deal with receiving data } }); t.Start(); string send_buffer = "Hello, world!"; client.Send(Encoding.ASCII.GetBytes(send_buffer)); running = false; t.Join(); }
public void RunReciever() { ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); try { // Setup the Socket ListenSocket.Bind(new IPEndPoint(IPAddress.Parse(p_HostIP), 0)); ListenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); ListenSocket.IOControl(unchecked((int) 0x98000001), new byte[4] {1, 0, 0, 0}, new byte[4]); while (true) //Infinite Loop keeps the Socket in Listen { ListenSocket.BeginReceive(p_PacketBuffer, 0, p_PacketBufferSize, SocketFlags.None, new AsyncCallback(CallReceive), this); while (ListenSocket.Available == 0) // If no Data Sleep the thread for 1ms then check to see if there is data to be read { Thread.Sleep(1); } } } catch (ThreadAbortException){}// Catch the ThreadAbort Exception that gets generated whenever a thread is closed with the Thread.Abort() method catch (Exception e) {new ErrorHandle(e);} finally //Shutdown the Socket when finished { if (ListenSocket != null) { ListenSocket.Shutdown(SocketShutdown.Both); ListenSocket.Close(); } } }
//BeginAcceptのコールバック private static void AcceptCallback(System.IAsyncResult ar) { allDone.Set(); //サーバーSocketの取得 System.Net.Sockets.Socket server = (System.Net.Sockets.Socket)ar.AsyncState; //接続要求を受け入れる System.Net.Sockets.Socket client = null; try { //クライアントSocketの取得 client = server.EndAccept(ar); } catch { System.Console.WriteLine("閉じました。"); return; } //クライアントが接続した時の処理をここに書く //ここでは文字列を送信して、すぐに閉じている client.Send(System.Text.Encoding.UTF8.GetBytes("こんにちは。")); Thread.Sleep(1000); client.Shutdown(System.Net.Sockets.SocketShutdown.Both); client.Close(); }
private void CloseTCPSocket(MySAE mysae) { try { if (_log && Data.Logger.IsDebugEnabled) { Data.Logger.Debug(String.Format("{0}:{1} TCP断开", mysae.Ip, mysae.Port)); } System.Net.Sockets.Socket s = mysae.UserToken as System.Net.Sockets.Socket; if (s != null && s.Connected) { try { s.Shutdown(SocketShutdown.Both); } catch { } s.Close(); } } catch (Exception ex) { Data.Logger.Error(ex); } }
public void close_socket() { m_isConnected = false; if (m_socket == null) { return; } if (!m_socket.Connected) { return; } try { m_socket.Shutdown(SocketShutdown.Both); } catch { //Log.ERROR("client socketId {0} close socket error, message: {1}", m_socketId, exp.Message); } try { m_socket.Close(); Log.INFO("client socketId {0} has been disconnected from the server", m_socketId); } catch { } }
public void InitUnix () { //TODO: /tmp/.X1-lock //string lockFile = "/tmp/.X" + 1 + "-lock"; string path = "/tmp/.X11-unix/X" + 1; UnixFileInfo ufi = new UnixFileInfo (path); UnixEndPoint ep = new UnixEndPoint (path); listener = new Socket (AddressFamily.Unix, SocketType.Stream, 0); //Bind creates the socket file right now listener.Bind (ep); //savedEP = listener.LocalEndPoint; //listen backlog 1 for now listener.Listen (1); Socket client = listener.Accept (); listener.Shutdown (SocketShutdown.Both); listener.Close (); ufi.Delete (); }
public ByteBuffer Read() { const int bufferSize = 4 * 1024; // TODO: Prevent constant allocation of buffers. byte[] bytes = new byte[bufferSize]; int numOctets = _networkStream.Read(bytes, 0, bytes.Length); /// Read only returns 0 if the socket has been gracefully shutdown. /// http://msdn2.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx /// We can use this to block Send so the next Read will force an exception forcing failover. /// Otherwise we need to wait ~20 seconds for the NetworkStream/Socket code to realise that /// the socket has been closed. if (numOctets == 0) { _socket.Shutdown(SocketShutdown.Send); _socket.Close(); } ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); byteBuffer.limit(numOctets); byteBuffer.flip(); return(byteBuffer); }
public override bool IsCloseSocket(Socket client) { if ((clientPool[client].buffer[0] | 0xf8) == 0xf8) { //把客户端标记为关闭,并在clientPool中清除 if (client != null && client.Connected) { //关闭Socket之前,首选需要把双方的Socket Shutdown掉 client.Shutdown(SocketShutdown.Both); //Shutdown掉Socket后主线程停止10ms,保证Socket的Shutdown完成 System.Threading.Thread.Sleep(10); //关闭客户端Socket,清理资源 client.Close(); Console.WriteLine("Client {0} disconnet", clientPool[client].Name); clientPool.Remove(client); devicePool.Remove(client); manageInfoPool.Remove(client); GetOnlineDeviceList(); } return true; } return false; }
static void SendMessage(int port) { byte[] bytes = new byte[1024]; IPAddress ipAddr = IPAddress.Parse("10.7.5.10"); //IPHostEntry ipHost = Dns.GetHostEntry("localhost"); //IPAddress ipAddr = ipHost.AddressList[0]; IPEndPoint ipEnd = new IPEndPoint(ipAddr, port); Socket sSender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sSender.Connect(ipEnd); Console.WriteLine("Enter your message:"); string message = Console.ReadLine(); Console.WriteLine("Client connect with {0}", sSender.RemoteEndPoint.ToString()); byte[] msg = Encoding.UTF8.GetBytes(message); int bytesSend = sSender.Send(msg); int bytesRec = sSender.Receive(bytes); Console.WriteLine("Answer from server : {0}", Encoding.UTF8.GetString(bytes,0,bytesRec)); if (message.IndexOf("<TheEnd>") == -1) SendMessage(port); sSender.Shutdown(SocketShutdown.Both); sSender.Close(); }
private void Shutdown(Exception shutdownReason) { lock (_shutdownLock) { if (_socketDisposed) { return; } // Make sure to close the connection only after the _aborted flag is set. // Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when // a BadHttpRequestException is thrown instead of a TaskCanceledException. _socketDisposed = true; // shutdownReason should only be null if the output was completed gracefully, so no one should ever // ever observe the nondescript ConnectionAbortedException except for connection middleware attempting // to half close the connection which is currently unsupported. _shutdownReason = shutdownReason ?? new ConnectionAbortedException("The Socket transport's send loop completed gracefully."); _trace.ConnectionWriteFin(ConnectionId, _shutdownReason.Message); try { // Try to gracefully close the socket even for aborts to match libuv behavior. _socket.Shutdown(SocketShutdown.Both); } catch { // Ignore any errors from Socket.Shutdown() since we're tearing down the connection anyway. } _socket.Dispose(); } }
//public void Beta(IPAddress target, int port) public void Beta() { IPAddress target = IPAddress.Parse("192.168.1.1"); IPEndPoint remote = new IPEndPoint(target, 22); string payload = new String('x', 1440); byte[] paybytes = Encoding.ASCII.GetBytes(payload); Socket send = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { send.Connect(remote); } catch (Exception e) { Console.WriteLine("Exception during socket connection/creation: {0}", e.ToString()); throw; } Console.WriteLine("\"Connected\" to {0}", send.RemoteEndPoint.ToString()); Console.WriteLine("Generating payload. Smoke meth and hail stan erryday."); Console.WriteLine("Brace for packets."); for (int i = 0; i < 666420; i++ ) { try { int bsent = send.Send(paybytes); } catch (Exception e) { Console.WriteLine("Unable to send packets. Balls. Error: {0}", e.ToString()); throw; } } Console.WriteLine("Shutting down the socket"); Console.WriteLine("Today was a good day."); send.Shutdown(SocketShutdown.Both); send.Close(); }
private void baseSend(object obj) { AbstractSocketData sockeData = obj as AbstractSocketData; SocketMessager socketMessager = new SocketMessager(); socketMessager.encode(sockeData); byte[] dataBytes = socketMessager.DataBytes; if (dataBytes != null && dataBytes.Length > 0) { System.Net.Sockets.Socket socket = null; try { System.Net.EndPoint remoteEP = new System.Net.IPEndPoint(this.ipAddress, this.port); socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); socket.SendTo(dataBytes, dataBytes.Length, System.Net.Sockets.SocketFlags.None, remoteEP); socket.Shutdown(System.Net.Sockets.SocketShutdown.Send); } catch (System.Exception) { } finally { if (socket != null) { socket.Close(); } } } }
private async void ProcessSocket(Socket socket) { Logger.Write("Connected from: " + socket.RemoteEndPoint); var session = new PacketSession(socket); _lock.DoWriteLock(() => _sessions.Add(session)); Dispatch(new ConnectionPacket { Connected = true }, session); try { while (true) { var packet = await session.Receive(); Dispatch(packet, session); } } catch (Exception e) { Logger.Write(e); } Dispatch(new ConnectionPacket {Connected = false}, session); _lock.DoWriteLock(() => _sessions.Remove(session)); try { socket.Shutdown(SocketShutdown.Both); } catch { } }
/// <summary> /// 开启服务,连接服务端 /// </summary> public void StartClient() { try { //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.0 创建IP对象 IPAddress address = IPAddress.Parse(_ip); //3.0 创建网络端口包括ip和端口 IPEndPoint endPoint = new IPEndPoint(address, _port); //4.0 建立连接 _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); _socket.Connect(endPoint); //Console.WriteLine("连接服务器成功"); //5.0 接收数据 int length = _socket.Receive(buffer); var t = string.Format("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length)); //6.0 像服务器发送消息 for (int i = 0; i < 10; i++) { Thread.Sleep(2000); string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString()); _socket.Send(Encoding.UTF8.GetBytes(sendMessage)); var tt = string.Format("像服务发送的消息:{0}", sendMessage); } } catch (Exception ex) { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); //Console.WriteLine(ex.Message); } //Console.WriteLine("发送消息结束"); ///Console.ReadKey(); }
public void CloseConnection() { try { if (WorkSocket != null) { if (WorkSocket.Connected) { try { WorkSocket.Shutdown(System.Net.Sockets.SocketShutdown.Send); } catch (Exception ex) { } WorkSocket.Close(); OnConnectionClosed(System.EventArgs.Empty); } if (WorkSocket != null) { WorkSocket.Dispose(); WorkSocket = null; } } } catch (Exception ex) { } }
public bool ResetSocket() { if (_connectState != NetworkClientState.Closed) { _connectState = NetworkClientState.Closed; try { if (_socket.Connected) { _socket.Shutdown(SocketShutdown.Both); _socket.Dispose(); } } finally { _socket.Close(); _socket = null; } _byteArray.Destroy(); _byteArray = null; return(true); } if (_unityInvoke != null) { _unityInvoke.Dispose(); _unityInvoke = null; } _isCalled = true; return(false); }
public void Dispose() { try { AddClient = null; RemoveClient = null; DataChange = null; DataRecive = null; DataSent = null; if (ListenerSocker != null) { ListenerSocker.Shutdown(SocketShutdown.Both); if (ListenerSocker.Connected) { ListenerSocker.Disconnect(true); } ListenerSocker.Close(); ListenerSocker.Dispose(); } for (int i = 0; i < Connections.Count; i++) { Connections[i].Close(); Connections[i].Dispose(); } } catch { } ListenerSocker = null; Connections = null; Log.Log.GetLog().Info(this, "Dispose"); GC.SuppressFinalize(this); }
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); } }
public void Connect(string message) { // Connect to a remote device. try { var ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 12000); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect(remoteEP, ConnectCallback, client); connectDone.WaitOne(); // Send test data to the remote device. Send(client, message); sendDone.WaitOne(); // Receive the response from the remote device. Receive(client); receiveDone.WaitOne(); // Release the socket. client.Shutdown(SocketShutdown.Both); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
static void Run() { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress HostIp = IPAddress.Parse("127.0.0.1"); socket.Connect(HostIp, 2626); BlinkConn conn = Blink.NewConnection(socket, 1024 * 1024, "D:/", Guid.NewGuid().ToString(), 0.001f, null, null); if (conn != null) { Console.WriteLine("Test Send String..."); for (int i = 0; i <= 50; i++) { string str = "Test String:" + i; conn.Send(str); Console.WriteLine(str); Thread.Sleep(2); if (IsExit) { conn.Dispose(); socket.Shutdown(SocketShutdown.Both); socket.Dispose(); socket.Close(); return; } } } }
public void StartListening() { byte[] bytes = new Byte[BufferSize]; IPHostEntry ipHostInfo = new IPHostEntry(); ipHostInfo.AddressList = new IPAddress[] { _serverIP}; IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { listener.BeginConnect(remoteEndPoint, new AsyncCallback(ConnectCallback), listener); connectDone.WaitOne(); // receive data receiveDone.Reset(); Receive(listener); receiveDone.WaitOne(); Console.WriteLine("Disconnecting from feed"); listener.Shutdown(SocketShutdown.Both); listener.Close(); } catch (Exception e) { Console.WriteLine("Feed Error " + e.ToString()); } }
public static void FullClose(this System.Net.Sockets.Socket s) { try { s.Shutdown(SocketShutdown.Both); } catch (Exception) { } try { s.Disconnect(false); } catch (Exception) { } try { s.Close(); } catch (Exception) { } try { s.Dispose(); } catch (Exception) { } }
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; }
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; }
/// <summary> /// Sends data to a specified IPAdress and port. /// </summary> /// <param name="data">The data to send as a string</param> /// <param name="adress">The address to send the data to</param> /// <param name="port">The port to send the data to</param> public static void SendData(string data, IPAddress adress, int port) { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // 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(adress, port); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes(data); // Send the data through the socket. int bytesSent = sender.Send(msg); // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (Exception e){ Console.WriteLine(e.ToString()); } } catch(Exception e){ Console.WriteLine (e.ToString ()); } }
static void Main(string[] args) { byte[] receiveBytes = new byte[1024]; //解析域名或者IP IPHostEntry ipHost = Dns.GetHostEntry("127.0.0.1"); //获取与主机关联的IP地址列表 IPAddress ipAddress = ipHost.AddressList[3]; //IP地址和端口号连接为一个节点 IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8008); Console.WriteLine("Starting: 创建 Socket 对象"); //创建发送socket实例 Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立远程主机连接 sender.Connect(ipEndPoint); Console.WriteLine("成功连接到:{0}", sender.RemoteEndPoint); string sendingMessage = "Hello my first socket test"; Console.WriteLine("信息:{0}", sendingMessage); byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]"); // 将数据发送到连接的Socket sender.Send(forwardMessage); //接受数据,写入缓冲区 int totalBytesRecevied = sender.Receive(receiveBytes); Console.WriteLine("准备从服务端接受信息:{0}", Encoding.ASCII.GetString(receiveBytes, 0, totalBytesRecevied)); sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.ReadLine(); }
private void ReleaseSocket() { mConnected = false; lock (this) { if (mSocket != null) { Handler.ClientDisposed(this); try { if (mSocket != null) { mSocket.Shutdown(SocketShutdown.Both); } } catch { } try { if (mSocket != null) { mSocket.Close(); } } catch { } } mSocket = null; } }
//------------------------------------------------------------------------------------------- public void Listen(string ipaddress, int port) { IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(ipaddress), port); Socket Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenersocket = Listener; try { Listener.Bind(ipendpoint); Listener.Listen((int) SocketOptionName.MaxConnections); DebugOut("Listening on: " + Listener.LocalEndPoint.ToString(), false); } catch(Exception e) { DebugOut("Failed to bind: " + e.Message, true); return; } while (!Listening && !Environment.HasShutdownStarted) { try { ThreadPool.QueueUserWorkItem(_OnAccept, Listener.Accept()); } catch { Thread.Sleep(100); } } Listener.Shutdown(SocketShutdown.Both); Listener.Close(); }
public void SentMessage(ServerFunctionsNames serverFunctionName, object data = null, string UserName = "******") { clientSocket = new Sockets.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(remoteEndPoint); var buffer = new byte[2048]; byte[] messageData = Serializer.Serialize(new SocketMessage(serverFunctionName.ToString(), UserName, data)); var messageSize = BitConverter.GetBytes(messageData.Count() + 4); var message = messageSize.Concat(messageData).ToArray(); clientSocket.Send(message); var recievedBytesCount = clientSocket.Receive(buffer); var recievedMessage = Serializer.Deserialize <SocketMessage>(buffer); ReflectionHelper.InvokeFunction(clientController, recievedMessage.CallbackFunction, new object[] { recievedMessage.Data }); clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } catch (Exception ex) { throw new Exception("Failed to send message to serwer"); } }
private void TryCloseSocket() { if (_inner_socket != null) { try { _inner_socket.Shutdown(SocketShutdown.Both); } catch (Exception e) { } try { _inner_socket.Disconnect(false); } catch (Exception e) { } try { _inner_socket.Close(); } catch (Exception e) { } /* #if !UNITY_EDITOR * try * { * _inner_socket.Dispose(); * } * catch (Exception e) { } #endif */ _inner_socket = null; } }
/* * Stops the server thread */ public void stopMainThread() { if (thread.IsAlive == true) { // Establish the remote endpoint for the socket. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11001); // Create a TCP/IP socket. Socket snder = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { stop = true; snder.Connect(remoteEP); } catch (Exception ex) { MessageBox.Show(ex.Message); } snder.Shutdown(SocketShutdown.Both); snder.Close(); // Abort watchdog thread also if (watchdog.IsAlive == true) { watchdog.Abort(); } } else { Application.Exit(); } }
public static void start() { IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client.Connect(new IPEndPoint(ip, 8888)); Console.WriteLine("connect success"); }catch { Console.WriteLine("connect failure"); return; } int receiveLen = client.Receive(result); Console.WriteLine("msg:{0}", Encoding.ASCII.GetString(result, 0, receiveLen)); ; try { Thread.Sleep(1000); string msg = "client msg:hello"; client.Send(Encoding.ASCII.GetBytes(msg)); } catch { client.Shutdown(SocketShutdown.Both); client.Close(); } Console.WriteLine("over"); }
public static void StartClient() { // 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. //IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); // 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("This is a test<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(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public static void Start_Client(System.Net.Sockets.Socket socket, IPEndPoint remoteEP) { // Data buffer byte[] bytes = new byte[1024]; // Connect to a server try { socket.Connect(remoteEP); status_label.Text = "connected"; // Receive data int bytesRec = socket.Receive(bytes); console_text.Buffer.Text = Encoding.ASCII.GetString(bytes, 0, bytesRec); socket.Shutdown(SocketShutdown.Both); socket.Close(); status_label.Text = "disconnected"; } catch (ArgumentNullException ane) { console_text.Buffer.Text = ane.ToString(); } catch (SocketException se) { console_text.Buffer.Text = se.ToString(); } catch (Exception e) { console_text.Buffer.Text = e.ToString(); } }
private static void Transfer(Socket socket) { int txDataLen = random.Next(maxDataLen); int rxDataLen; TransferHeaders(socket, txDataLen, out rxDataLen); // System.Console.WriteLine ("txDataLen="+txDataLen+" rxDataLen="+rxDataLen); socket.Blocking = false; socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); // Disable the Nagle algorithm for send coalescing. int txPos = 0; int rxPos = 0; while (txPos < txDataLen || rxPos < rxDataLen) { // System.Console.WriteLine ("txPos="+txPos+"/"+txDataLen+" rxPos="+rxPos+"/"+rxDataLen); int txReqLen = Math.Min(txDataLen - txPos, 1 + random.Next(maxBlockLen)); int txTrLen = Send(socket, txReqLen); txPos += txTrLen; int rxReqLen = Math.Min(rxDataLen - rxPos, maxBlockLen); int rxTrLen = Receive(socket, rxReqLen); rxPos += rxTrLen; if (random.Next(1000) == 0) { Thread.Sleep(50); } else if ((txTrLen < txReqLen && rxTrLen < rxReqLen) || random.Next(50) == 0) { Thread.Sleep(1); } } socket.Shutdown(SocketShutdown.Both); }
/// <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; }
public void Shutdown(SocketShutdown how) { #if UDT_FULLTCP _tcpSocket.Shutdown(how); #else API_Shutdown(_handle, (int)how); #endif }
/** * Closes the socket connection. */ public void Disconnect() { if (Connected) { penguinSocks.Shutdown(Sockets.SocketShutdown.Both); penguinSocks.Disconnect(true); } }
void IPeer.Close() { if (_Socket.Connected) { _Socket.Shutdown(SocketShutdown.Both); } _Socket.Close(); }
public void OnReceived(IAsyncResult ar) { try { System.Net.Sockets.Socket sock = (System.Net.Sockets.Socket)ar.AsyncState; int nBytesRec = sock.EndReceive(ar); if (nBytesRec > 0) { // Read the message int bytesRead = sock.Receive(m_byBuff, BitConverter.ToInt32(m_msg_header, 0), SocketFlags.None); // Wrote the data to the List string received = Encoding.ASCII.GetString(m_byBuff, 0, bytesRead); JObject obj = JObject.Parse(received); if (obj["type"].ToString() == "message") { string severity = obj["severity"].ToString(); string message = obj["message"].ToString(); if (severity == "info") { WriteLog(message, tagInfo); } else if (severity == "warning") { WriteLog(message, tagWarning); } else if (severity == "error") { WriteLog(message, tagError); } else if (severity == "debug") { WriteLog(message, tagDebug); } } else { WriteLog("Unknown response from server\n", tagInfo); } // If the connection is still usable restablish the callback Receive(sock); } else { // If no data was recieved then the connection is probably dead WriteLog("Server closed connection\n", tagInfo); sock.Shutdown(SocketShutdown.Both); sock.Close(); } } catch (Exception ex) { WriteLog("Unknown error during receive\n", tagInfo); } }
public void Disconect() { if (sender != null) { sender.Shutdown(SocketShutdown.Both); sender.Close(); isConected = false; } }
public void Close() { if (_Socket.Connected) { _Socket.Shutdown(SocketShutdown.Both); } _Socket.Close(); }
/// <summary> This method closes and cleans up the socket.</summary> public void Close() { // Release the socket. if (_socket != null) { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); } }
void IListenable.Close() { if (_Socket.Connected) { _Socket.Shutdown(SocketShutdown.Both); } _Socket.Close(); }
public void Dispose() { DebugQy.LogTag("ClientSocket", "Disposed !!!!!!!!", "#BB7979FF"); if (m_clientSocket.Connected) { m_clientSocket.Shutdown(SocketShutdown.Both); m_clientSocket.Close(); } }
// 释放对象 internal void Dispose() { if (Interlocked.CompareExchange(ref DisposedCAS, 1, 0) == 0) // CAS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock ) // Lock objects : InnerSocket { LOCK(ref InnerSocketLockRoot); try { if (InnerSocket.Connected) { InnerSocket.Shutdown(SocketShutdown.Both); } InnerSocket.Close(); } finally { UNLOCK(ref InnerSocketLockRoot); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock ) if (ConnectArgs != null) { ConnectArgs.Dispose(); } if (SendArgs != null) { SendArgs.Dispose(); } if (ReceivingMessage != null) { ReceivingMessage.Dispose(); } if (SendingMessage != null) { SendingMessage.Dispose(); } // 归还缓冲区 BufferHandler.RecyclingBuffer(ReceiveBuffer); ReceiveBuffer = null; // 清空并释放接收消息队列 int length = ReceiveMessageQueue.Count; for (int i = 0; i < length; i++) { ReceiveMessageQueue[i].Dispose(); } ReceiveMessageQueue.RemoveRange(0, length); // 清空并释放发送消息队列 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock ) // Lock objects : SendMessageQueue LOCK(ref SendMessageQueueLockRoot); try { length = SendMessageQueue.Count; for (int i = 0; i < length; i++) { SendMessageQueue[i].Dispose(); } SendMessageQueue.RemoveRange(0, length); } finally { UNLOCK(ref SendMessageQueueLockRoot); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock ) } }
public void ServerThreadProc() { while (true) { try { // 處理用戶端連線 clientSocket = tcpListener.AcceptSocket(); // 取得本機相關的網路資訊 IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint; // 取得連線用戶端相關的網路連線資訊 IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint; Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString()); Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString()); // 設定接收資料緩衝區 byte[] bytes = new Byte[1024]; // 自已連線的用戶端接收資料 int bytesReceived = clientSocket.Receive(bytes, 0, bytes.Length, SocketFlags.None); if (bytesReceived > 0) { Console.WriteLine("接收位元組數目: {0}", bytesReceived); Console.WriteLine("接收的資料內容: \r\n" + "{0}", Encoding.UTF8.GetString(bytes, 0, bytesReceived) + "\r\n"); } // 測試用 string htmlBody = "<html><head><title>Send Test</title></head><body><font size=2 face=Verdana>Sent OK.</font></body></html>"; string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" + "Server: HTTP Server 1.0" + "\r\n" + "Content-Type: text/html" + "\r\n" + "Content-Length: " + htmlBody.Length + "\r\n\r\n"; string htmlContent = htmlHeader + htmlBody; // 設定傳送資料緩衝區 byte[] msg = Encoding.ASCII.GetBytes(htmlContent); // 傳送資料至已連線的用戶端 int bytesSend = clientSocket.Send(msg, 0, msg.Length, SocketFlags.None); Console.WriteLine("傳送位元組數目: {0}", bytesSend); Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", Encoding.UTF8.GetString(msg, 0, bytesSend) + "\r\n"); // 同時暫停用戶端的傳送和接收作業 clientSocket.Shutdown(SocketShutdown.Both); // 關閉用戶端Socket clientSocket.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); } } }