public Tracker(string configfile) { Configuration = new TrackerConfig(configfile); Logger.Active = Configuration.Log; peers = new Dictionary<int, Peer>(); rooms = new Dictionary<string, Room>(); // Listening on socket IPAddress ipAddr = IPAddress.Parse(Configuration.IPAddress); IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Configuration.Port); SocketPermission permission = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", Configuration.Port); permission.Demand(); try { listener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listener.Bind(ipEndPoint); Console.WriteLine("Listening at IP " + ipEndPoint.Address + " and port " + ipEndPoint.Port + "."); listener.Listen(Configuration.Backlog); AsyncCallback aCallback = new AsyncCallback(AcceptCallback); listener.BeginAccept(aCallback, listener); } catch (SocketException exc) { Logger.WriteLine(exc); } }
public void Connect() { if (c == null) return; SocketPermission permission = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted); permission.Demand(); IPHostEntry heserver = Dns.Resolve(c.XMLConf.Host); IPAddress iadd = (IPAddress)heserver.AddressList[0]; IPEndPoint ip = new IPEndPoint(iadd, c.XMLConf.Port); s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, 1); while(!s.Connected) { try { s.Connect(ip); } catch (Exception e) { //MessageBox.Show("Verbindung fehlgeschlagen! "+e.Message); c.use_network = false; Thread.Sleep(1000); } } c.use_network = true; SendHelloToZusi(s); }
public void Connect(ref Socket s, string server, int port, string id) { SocketPermission permission = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted); permission.Demand(); IPHostEntry heserver = Dns.Resolve(server); IPAddress iadd = (IPAddress)heserver.AddressList[0]; IPEndPoint ip = new IPEndPoint(iadd, port); s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); //s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1); //s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, 1); while(!s.Connected) { try { s.Connect(ip); } catch (Exception e) { //MessageBox.Show("Verbindung fehlgeschlagen! "+e.Message); m_net.SetConnected(false); Thread.Sleep(1000); } } m_net.SetConnected(true); client_id = id; SendHelloToZusi(s); }
static Socket CreateBoundSocket(IPEndPoint endpoint) { // demand permission var permission = new SocketPermission( NetworkAccess.Connect, TransportType.Tcp, endpoint.Address.ToString(), endpoint.Port); permission.Demand(); // create a tcp socket to listen var socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(endpoint); return socket; }
/// <summary> /// /// </summary> /// <param name="asClient"></param> /// <returns></returns> public IConnection Connect(bool asClient) { _asClient = asClient; var _permission = new SocketPermission( NetworkAccess.Accept, // Allowed to accept connections TransportType.Tcp, // Defines transport types "", // The IP addresses of local host SocketPermission.AllPorts // Specifies all ports ); _permission.Demand(); IPAddress ipAddress = null; if (_address != null) { ipAddress = IPAddress.Parse(_address); } else { // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry(""); ipAddress = ipHost.AddressList[0]; } var _endPoint = new IPEndPoint(ipAddress, _port); // Create one Socket object to setup Tcp connection var _socket = new Socket( ipAddress.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); _socket.NoDelay = false; // Using the Nagle algorithm // Establishes a connection to a remote host if (asClient) { _socket.Connect(_endPoint); } else { _socket.Bind(_endPoint); _socket.Listen(10); _socket.NoDelay = false; } return new TcpConnection<MessageBuilder>(_socket) { IsClient = asClient}; }
private void Start_Click(object sender, RoutedEventArgs e) { try { // Creates one SocketPermission object for access restrictions permission = new SocketPermission( NetworkAccess.Accept, // Allowed to accept connections TransportType.Tcp, // Defines transport types "", // The IP addresses of local host SocketPermission.AllPorts // Specifies all ports ); // Listening Socket object sListener = null; // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry(""); // Gets first IP address associated with a localhost //IPAddress ipAddr = ipHost.AddressList[1]; IPAddress ipAddr = IPAddress.Parse("172.20.95.232"); // Creates a network endpoint ipEndPoint = new IPEndPoint(ipAddr, 4510); // Create one Socket object to listen the incoming connection sListener = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); // Associates a Socket with a local endpoint sListener.Bind(ipEndPoint); tbStatus.Text = "Server started."; Start_Button.IsEnabled = false; StartListen_Button.IsEnabled = true; } catch (Exception exc) { MessageBox.Show(exc.ToString()); } }
private void Connect_Click(object sender, RoutedEventArgs e) { try { // Create one SocketPermission for socket access restrictions SocketPermission permission = new SocketPermission( NetworkAccess.Connect, // Connection permission TransportType.Tcp, // Defines transport types "", // Gets the IP addresses SocketPermission.AllPorts // All ports ); // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry("Pc-TOSH"); // Gets first IP address associated with a localhost IPAddress ipAddr = ipHost.AddressList[1]; //IPAddress ipAdress = IPAddress.Parse("10.76.175.31"); // Creates a network endpoint IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510); // Create one Socket object to setup Tcp connection senderSock = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); senderSock.NoDelay = false; // Using the Nagle algorithm // Establishes a connection to a remote host senderSock.Connect(ipEndPoint); tbStatus.Text = "Socket connected to " + senderSock.RemoteEndPoint.ToString(); Connect_Button.IsEnabled = false; Send_Button.IsEnabled = true; } catch (Exception exc) { MessageBox.Show(exc.ToString()); } }
protected override SocketPermission GetPermission() { try { SocketPermission permission = new SocketPermission ( NetworkAccess.Connect, TransportType.Tcp, _host, SocketPermission.AllPorts ); permission.Demand(); return permission; } catch (Exception e) { _boundary.Notify(e.ToString()); return null; } }
private void start_the_server() { try { // Creates one SocketPermission object for access restrictions permission = new SocketPermission( NetworkAccess.Accept, // Allowed to accept connections TransportType.Tcp, // Defines transport types "", // The IP addresses of local host SocketPermission.AllPorts // Specifies all ports ); // Listening Socket object sListener = null; // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry(""); // Gets first IP address associated with a localhost IPAddress ipAddr = ipHost.AddressList[0]; // Creates a network endpoint ipEndPoint = new IPEndPoint(ipAddr, 4610); // Create one Socket object to listen the incoming connection sListener = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); // Associates a Socket with a local endpoint sListener.Bind(ipEndPoint); lbl_server_status.Text = "Server started Successfully."; } catch (Exception exc) { MessageBox.Show(exc.ToString()); } }
internal static Socket Start() { SocketPermission permission; Socket sListener; IPEndPoint ipEndPoint; // Creates one SocketPermission object for access restrictions permission = new SocketPermission( NetworkAccess.Accept, // Allowed to accept connections TransportType.Tcp, // Defines transport types "", // The IP addresses of local host SocketPermission.AllPorts // Specifies all ports ); // Listening Socket object sListener = null; // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry(""); // Gets first IP address associated with a localhost IPAddress ipAddr = ipHost.AddressList[1]; //IPAddress ipAddr = IPAddress.Parse("172.20.95.232"); // Creates a network endpoint ipEndPoint = new IPEndPoint(ipAddr, 4510); // Create one Socket object to listen the incoming connection sListener = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); // Associates a Socket with a local endpoint sListener.Bind(ipEndPoint); return sListener; }
private void Window_Loaded(object sender, RoutedEventArgs e) { SocketPermission perm = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, robotAddress, 8027); perm.Demand(); IPAddress ipAddr = IPAddress.Parse(robotAddress); IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 8027); senderSock = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); senderSock.NoDelay = false; senderSock.Connect(ipEndPoint); statusTextBlock.Text = "Spojeno s " + senderSock.RemoteEndPoint.ToString() + "."; DispatcherTimer dt = new DispatcherTimer(); dt.Tick += new EventHandler(dt_Tick); dt.Interval = new TimeSpan(0, 0, 1); dt.Start(); /*if (phoneAddress != "") { myControl.MediaPlayer.Play(new Uri("http://" + phoneAddress + ":8080/mjpeg/")); }*/ }
/// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.Bind"]/*' /> /// <devdoc> /// <para>Associates a socket with an end point.</para> /// </devdoc> public void Bind(EndPoint localEP) { if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // // parameter validation // if (localEP==null) { throw new ArgumentNullException("localEP"); } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() localEP:" + localEP.ToString()); EndPoint endPointSnapshot = localEP; // // for now security is implemented only on IPEndPoint // If EndPoint is of other type - unmanaged code permisison is demanded // if (endPointSnapshot.GetType()==typeof(IPEndPoint)) { // // cast the EndPoint to IPEndPoint // endPointSnapshot = new IPEndPoint(((IPEndPoint)localEP).Address, ((IPEndPoint)localEP).Port); IPEndPoint localIPEndPoint = (IPEndPoint)endPointSnapshot; // // create the permissions the user would need for the call // SocketPermission socketPermission = new SocketPermission( NetworkAccess.Accept, Transport, localIPEndPoint.Address.ToString(), localIPEndPoint.Port); // // demand for them // socketPermission.Demand(); // Here the permission check has succeded. // NB: if local port is 0, then winsock will assign some>1024, // so assuming that this is safe. We will not check the // NetworkAccess.Accept permissions in Receive. } else { (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand(); } // // ask the EndPoint to generate a SocketAddress that we // can pass down to winsock // SocketAddress socketAddress = endPointSnapshot.Serialize(); int errorCode = UnsafeNclNativeMethods.OSSOCK.bind( m_Handle, socketAddress.m_Buffer, socketAddress.m_Size ); // // if the native call fails we'll throw a SocketException // if (errorCode!=SocketErrors.Success) { // // update our internal state after this socket error and throw // SocketException socketException = new SocketException(); UpdateStatusAfterSocketError(); throw socketException; } if (m_RightEndPoint==null) { // // save a copy of the EndPoint so we can use it for Create() // m_RightEndPoint = endPointSnapshot; } }
static void Main(string[] args) { try { // Resolves a host name to an IPHostEntry instance var ipHost = Dns.GetHostEntry(""); // Gets first IP address associated with a localhost IPAddress ipAddr = ipHost.AddressList[3]; // Creates a network endpoint var ipEndPoint = new IPEndPoint(ipAddr, PORT); // Creates one SocketPermission object for access restrictions var permission = new SocketPermission( NetworkAccess.Accept, // Allowed to accept connections TransportType.Tcp, // Defines transport types "", // The IP addresses of local host SocketPermission.AllPorts // Specifies all ports ); // Ensures the code to have permission to access a Socket permission.Demand(); // Create one Socket object to listen the incoming connection var listener = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Associates a Socket with a local endpoint listener.Bind(ipEndPoint); Console.WriteLine("The server has started."); // Places a Socket in a listening state and specifies the maximum // Length of the pending connections queue listener.Listen(MAX_CONNECTION); // Begins an asynchronous operation to accept an attempt var callback = new AsyncCallback(AcceptCallback); listener.BeginAccept(callback, listener); Console.WriteLine("The server is listening on {0} port {1}", ipEndPoint.Address, ipEndPoint.Port.ToString()); while (true) { System.Threading.Thread.Sleep(100); } } catch (Exception e) { Console.WriteLine("ERROR: " + e.Message); } }
public bool Open(int ASocketHandle) { if (OSUtils.IsWindows) { try { NativeMethods.WSAData WSA = new NativeMethods.WSAData(); SocketError Result = NativeMethods.WSAStartup((short)0x0202, out WSA); if (Result != SocketError.Success) throw new SocketException(NativeMethods.WSAGetLastError()); SocketPermission SP = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted); SP.Demand(); SocketInformation SI = new SocketInformation(); SI.Options = SocketInformationOptions.Connected; SI.ProtocolInformation = new byte[Marshal.SizeOf(typeof(NativeMethods.WSAPROTOCOL_INFO))]; Result = SocketError.Success; unsafe { fixed (byte* pinnedBuffer = SI.ProtocolInformation) { Result = NativeMethods.WSADuplicateSocket(new IntPtr(ASocketHandle), (uint)Process.GetCurrentProcess().Id, pinnedBuffer); } } if (Result != SocketError.Success) throw new SocketException(NativeMethods.WSAGetLastError()); return Open(new Socket(SI)); } catch (SocketException sex) { RMLog.Exception(sex, "SocketException in TcpConnection::Open(). ErrorCode=" + sex.ErrorCode.ToString()); return false; } catch (Exception ex) { RMLog.Exception(ex, "Exception in TcpConnection::Open()"); return false; } } else { try { SocketInformation SI = new SocketInformation(); SI.Options = SocketInformationOptions.Connected; SI.ProtocolInformation = new byte[24]; // From Mono's Socket.cs DuplicateAndClose() SI.ProtocolInformation = Mono.DataConverter.Pack("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, isbound ? 1 : 0, (long)socket); byte[] B1 = BitConverter.GetBytes((int)AddressFamily.InterNetwork); byte[] B2 = BitConverter.GetBytes((int)SocketType.Stream); byte[] B3 = BitConverter.GetBytes((int)ProtocolType.Tcp); byte[] B4 = BitConverter.GetBytes((int)1); byte[] B5 = BitConverter.GetBytes((long)ASocketHandle); Array.Copy(B1, 0, SI.ProtocolInformation, 0, B1.Length); Array.Copy(B2, 0, SI.ProtocolInformation, 4, B2.Length); Array.Copy(B3, 0, SI.ProtocolInformation, 8, B3.Length); Array.Copy(B4, 0, SI.ProtocolInformation, 12, B4.Length); Array.Copy(B5, 0, SI.ProtocolInformation, 16, B5.Length); return Open(new Socket(SI)); } catch (SocketException sex) { RMLog.Exception(sex, "SocketException in TcpConnection::Open(). ErrorCode=" + sex.ErrorCode.ToString()); return false; } catch (Exception ex) { RMLog.Exception(ex, "Exception in TcpConnection::Open()"); return false; } } }
// // socketAddress must always be the result of remoteEP.Serialize() // private SocketAddress CheckCacheRemote(ref EndPoint remoteEP, bool isOverwrite) { IPEndPoint ipSnapshot = remoteEP as IPEndPoint; if (ipSnapshot != null) { // Snapshot to avoid external tampering and malicious derivations if IPEndPoint ipSnapshot = ipSnapshot.Snapshot(); // DualMode: Do the security check on the user input address, but return an IPEndPoint // mapped to an IPv6 address. remoteEP = RemapIPEndPoint(ipSnapshot); } // This doesn't use SnapshotAndSerialize() because we need the ipSnapshot later. SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(remoteEP); // We remember the first peer we have communicated with SocketAddress permittedRemoteAddress = m_PermittedRemoteAddress; if (permittedRemoteAddress != null && permittedRemoteAddress.Equals(socketAddress)) { return permittedRemoteAddress; } // // for now SocketPermission supports only IPEndPoint // if (ipSnapshot != null) { // // create the permissions the user would need for the call // SocketPermission socketPermission = new SocketPermission( NetworkAccess.Connect, Transport, ipSnapshot.Address.ToString(), ipSnapshot.Port); // // demand for them // socketPermission.Demand(); } else { // // for V1 we will demand permission to run UnmanagedCode for // an EndPoint that is not an IPEndPoint until we figure out how these fit // into the whole picture of SocketPermission // ExceptionHelper.UnmanagedPermission.Demand(); } //cache only the first peer we communicated with if (m_PermittedRemoteAddress == null || isOverwrite) { m_PermittedRemoteAddress = socketAddress; } return socketAddress; }
public bool JoinRoom(string roomId) { try { if ((IsConnected) && (!IsInRoom)) { Logger.WriteLine("Requesting to join room " + roomId); Message request = Message.CreateMessageJoin(PeerId, roomId); byte[] buffer = new byte[1024]; lock (trackerPaddle) { trackerSocket.Send(request.data, 0, request.data.Length, SocketFlags.None); trackerSocket.Receive(buffer, buffer.Length, SocketFlags.None); } Message response = new Message(buffer); Message.MessageType responseType = response.GetMessageType(); if (responseType == Message.MessageType.CreatorInfo) { IPAddress ip; int port; response.GetCreatorInfo(out ip, out port); Logger.WriteLine("GunbondPeer (Peer - Tracker): Creator Info"); Logger.WriteLine("Hostname : " + ip); Logger.WriteLine("Port : " + port); SocketPermission permission = new SocketPermission( NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts ); permission.Demand(); byte[] bufferFromCreator = new byte[1024]; lock (nextPeerPaddle) { IPEndPoint ipEndPoint = new IPEndPoint(ip, port); nextPeerSocket = new Socket( ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); nextPeerSocket.NoDelay = false; nextPeerSocket.Connect(ipEndPoint); Message messageConnectToCreator = Message.CreateMessageHandshakePeerCreator(PeerId, Configuration.ListenPort); nextPeerSocket.Send(messageConnectToCreator.data, 0, messageConnectToCreator.data.Length, SocketFlags.None); nextPeerSocket.Receive(bufferFromCreator, bufferFromCreator.Length, SocketFlags.None); } keepAliveRoom = new Thread(new ThreadStart(SendAliveNextPeer)); keepAliveRoom.Start(); Message messageFromCreator = new Message(bufferFromCreator); Message.MessageType fromCreatorMessageType = messageFromCreator.GetMessageType(); if (fromCreatorMessageType == Message.MessageType.Success) { IsInRoom = true; IsCreator = false; Logger.WriteLine("Successfully joined room."); return true; } else { Logger.WriteLine("Request join room failed 1."); return false; } } else if (responseType == Message.MessageType.Failed) { Console.WriteLine("Request join room failed 2."); return false; } else { Console.WriteLine("Response unrecognized."); return false; } } else if (!IsConnected) { Console.WriteLine("Not connected to tracker, connect to tracker first."); return false; } else if (IsInRoom) { Console.WriteLine("Currently in room, quit room first."); return false; } else { Console.WriteLine("Unknown error."); return false; } } catch (Exception exc) { Console.WriteLine(exc.ToString()); return false; } }
public async Task Attach(CancellationToken cancellationToken) { System.Diagnostics.Debug.Assert(CurrentState == State.Idle); SocketPermission permission = new SocketPermission( NetworkAccess.Connect, TransportType.Tcp, kServerHostname, kServerPort); permission.Demand(); IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 }); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, kServerPort); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Blocking = false; socket.NoDelay = true; socket.ReceiveBufferSize = 1024 * 1024; socket.SendBufferSize = 1024 * 1024; socket.ReceiveTimeout = 0; socket.SendTimeout = 0; OnStateChanged(State.Attaching); while (true) { Task task = Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, ipEndPoint, null); try { await task.WithCancellation(cancellationToken); } catch (OperationCanceledException) { socket.Close(); socket = null; OnStateChanged(State.Idle); return; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionRefused) { // Not found - emulator may still be starting. System.Diagnostics.Debug.WriteLine("Connection refused; trying again..."); continue; } OnStateChanged(State.Idle); return; } break; } // Start recv pump. Dispatch.Issue(() => ReceivePump()); var fbb = BeginRequest(); AttachRequest.StartAttachRequest(fbb); int requestDataOffset = AttachRequest.EndAttachRequest(fbb); var response = await CommitRequest(fbb, RequestData.AttachRequest, requestDataOffset); System.Diagnostics.Debug.Assert(response.ResponseDataType == ResponseData.AttachResponse); var attachResponse = new AttachResponse(); response.GetResponseData(attachResponse); // Open mmap to share memory. memoryHandle = FileMapping.OpenFileMapping( FileMapAccess.FILE_MAP_ALL_ACCESS, false, attachResponse.MemoryFile); if (memoryHandle.IsInvalid) { System.Diagnostics.Debug.Fail("Unable to open target memory"); Detach(); return; } // Open mmap to code cache. codeCacheHandle = FileMapping.OpenFileMapping(FileMapAccess.FILE_MAP_ALL_ACCESS, false, attachResponse.CodeCacheFile); if (codeCacheHandle.IsInvalid) { System.Diagnostics.Debug.Fail("Unable to open target code cache"); Detach(); return; } codeCachePtr = FileMapping.MapViewOfFileEx( codeCacheHandle, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0, attachResponse.CodeCacheSize, attachResponse.CodeCacheBase); // Setup the memory system. This maps the emulator memory into our address // space. if (!Memory.InitializeMapping(memoryHandle)) { Detach(); return; } OnStateChanged(State.Attached); }
public Client() { var perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts); perm.Demand(); }
private void _btnRegister_Click(object sender, RoutedEventArgs e) { try { // Create one SocketPermission for socket access restrictions SocketPermission permission = new SocketPermission( NetworkAccess.Connect, // Connection permission TransportType.Tcp, // Defines transport types "", // Gets the IP addresses SocketPermission.AllPorts // All ports ); // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance //IPHostEntry ipHost = Dns.GetHostEntry(""); // Creates a network endpoint IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port); // Create one Socket object to setup Tcp connection senderSock = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); senderSock.NoDelay = false; // Using the Nagle algorithm // Establishes a connection to a remote host senderSock.Connect(ipEndPoint); GUI_Log("connecting reg-server: " + ((IPEndPoint)(senderSock.RemoteEndPoint)).Address); SendRegisterMessage(); } catch (Exception)//ex) { GUI_Log("RegServer not reachable, please try again later!"); //MessageBox.Show("LoginServer not reachable, please try again later!","connection error",MessageBoxButton.OK); //MessageBox.Show(ex.ToString()); } }
public void Start() { if (!isStarted) { try { // Create one SocketPermission for socket access restrictions SocketPermission permission = new SocketPermission( NetworkAccess.Connect, // Connection permission TransportType.Tcp, // Defines transport types "", // Gets the IP addresses SocketPermission.AllPorts // All ports ); // Ensures the code to have permission to access a Socket permission.Demand(); IPAddress ipAddr = IPAddress.Parse(ip); // Creates a network endpoint IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port); // Create one Socket object to setup Tcp connection socket = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); Configure(); // Establishes a connection to a remote host socket.Connect(ipEndPoint); logger.Debug(m => m("Socket connected to {0}", socket.RemoteEndPoint.ToString())); } catch (Exception ex) { logger.Error(ex); } } isStarted = true; }
// // socketAddress must always be the result of remoteEP.Serialize() // private void CheckCacheRemote(SocketAddress socketAddress, EndPoint remoteEP, bool isOverwrite) { // We remember the first peer we have communicated with if (m_PermittedRemoteAddress != null && m_PermittedRemoteAddress.Equals(socketAddress)) { return; } // // for now SocketPermission supports only IPEndPoint // if (remoteEP.GetType()==typeof(IPEndPoint)) { // // cast the EndPoint to IPEndPoint // IPEndPoint remoteIPEndPoint = (IPEndPoint)remoteEP; // // create the permissions the user would need for the call // SocketPermission socketPermission = new SocketPermission( NetworkAccess.Connect, Transport, remoteIPEndPoint.Address.ToString(), remoteIPEndPoint.Port); // // demand for them // socketPermission.Demand(); } else { // // for V1 we will demand permission to run UnmanagedCode for // an EndPoint that is not an IPEndPoint until we figure out how these fit // into the whole picture of SocketPermission // (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand(); } //cache only the first peer we communicated with if (m_PermittedRemoteAddress == null || isOverwrite) { m_PermittedRemoteAddress = socketAddress; } }
/// <summary>Associates a <see cref="T:namespace SockCel.Socket" /> with a local endpoint.</summary> /// <param name="localEP">The local <see cref="T:System.Net.EndPoint" /> to associate with the <see cref="T:namespace SockCel.Socket" />. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="localEP" /> is null. </exception> /// <exception cref="T:namespace SockCel.SocketException">An error occurred when attempting to access the socket. See the Remarks section for more information. </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:namespace SockCel.Socket" /> has been closed. </exception> /// <exception cref="T:System.Security.SecurityException">A caller higher in the call stack does not have permission for the requested operation. </exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// <IPermission class="System.Net.SocketPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// </PermissionSet> public void Bind(EndPoint localEP) { if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } if (localEP == null) { throw new ArgumentNullException("localEP"); } EndPoint endPoint = localEP; IPEndPoint iPEndPoint = localEP as IPEndPoint; if (iPEndPoint != null) { endPoint = this.RemapIPEndPoint(iPEndPoint); SocketPermission socketPermission = new SocketPermission(NetworkAccess.Accept, this.Transport, iPEndPoint.Address.ToString(), iPEndPoint.Port); socketPermission.Demand(); } SocketAddress socketAddress = this.CallSerializeCheckDnsEndPoint(endPoint); this.DoBind(endPoint, socketAddress); }
public void start(string ip, int port, int number) { Log.Info("正在启动监听"); SocketPermission permission = new SocketPermission( NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts ); Socket sListener = null; try { permission.Demand(); IPAddress ipAddr = IPAddress.Parse(ip); IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port); sListener = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); sListener.Bind(ipEndPoint); sListener.Listen(number); Log.Info(string.Format("监听已启动在 {0}", ipEndPoint)); sListener.BeginAccept(new AsyncCallback(AcceptCallback), sListener); } catch (Exception ex) { Console.WriteLine("Server Error : {0}", ex.ToString()); Log.Debug(string.Format("ERROR : {0}", ex.Message)); return; } if (sListener.Connected) { sListener.Shutdown(SocketShutdown.Receive); sListener.Close(); } }
//Ethernet private Error Crea_PRN_Socket(Terminal ter) { string nombre1, nombre2, nombre3, port1, port2, port3, tel1, tel2, tel3; Conexion cxn = new Conexion(); Error cxnErr = new Error(); IPHostEntry ipHost; IPAddress ipAddr; try { #region // PROCESO DE CONEXIÓN IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); for (int i = 0; i < ipHostInfo.AddressList.Length; i++) { TransacManager.ProtoConfig.LOCAL_IP = ipHostInfo.AddressList[i]; //----------- Cambia de 1 elemento a 2. if (TransacManager.ProtoConfig.LOCAL_IP.AddressFamily == AddressFamily.InterNetwork) break; } IPEndPoint localEndPoint = new IPEndPoint(TransacManager.ProtoConfig.LOCAL_IP, TransacManager.ProtoConfig.LOCAL_PORT); bool sale = false; int fusible = 0; while (sale == false) // INTENTA HASTA CONECTAR CON PRN { SocketPermission permission = new SocketPermission(PermissionState.Unrestricted //NetworkAccess.Connect, // Connection permission //TransportType.Tcp, // Defines transport types //"", // Gets the IP addresses //SocketPermission.AllPorts // All ports ); //SocketPermissionAttribute per = new SocketPermissionAttribute(SecurityAction. permission.Demand(); string res = cxn.Leer_XMLprn(out nombre1, out nombre2, out nombre3, out port1, out port2, out port3, out tel1, out tel2, out tel3, TransacManager.ProtoConfig.CONFIG); if (res == null && TransacManager.ProtoConfig.CON_CICLO_PRN) // EXISTE PRN { #region // INTENTA CONECTAR CON PRN string[] nom = { nombre1, nombre2, nombre3 }; string[] por = { port1, port2, port3 }; string[] tel = { tel1, tel2, tel3 }; for (int j = 0; j < 3; j++) { try { ipHost = Dns.GetHostEntry(nom[j]); if (ipHost is IPHostEntry) { ipAddr = null; for (int i = 0; i < ipHost.AddressList.Length; i++) { ipAddr = ipHost.AddressList[i]; //----------- Cambia de 1 elemento a 2. if (ipAddr.AddressFamily == AddressFamily.InterNetwork) break; } LogBMTP.LogMessage("Resulve DNS: " + nom[j] + " - " + ipAddr, lvlLogCxn, TimeStampLog); ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(por[j])); sender = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); sender.NoDelay = false; // Using the Nagle algorithm sender.ReceiveTimeout = ProtocoloConfig.TimeoutSocket; sender.SendTimeout = ProtocoloConfig.TimeoutSocket; sender.Bind(localEndPoint); sender.Connect(ipEndPoint); } } catch (Exception e) { ipHost = null; LogBMTP.LogMessage(" Intento con " + nom[j] + "(" + j + ") falló. \n" + e.Message + " " + e.InnerException, lvlLogDebug, TimeStampLog); if (sender != null) sender.Close(); } if (sender != null && sender.Connected == true) { UltimaConexionOptima[0] = nom[j]; UltimaConexionOptima[1] = por[j]; UltimaConexionOptima[2] = tel[j]; sale = true; break; } } #endregion if (fusible >= 2 && sale == false) { sale = true; cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKET; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación. Se superaron los intentos de conexión."; cxnErr.Estado = 0; break; } if (sender == null || sender.Connected != true) { #region // FALLÓ PRN, INTENTA CON CONFIG.BIN cxn.Borrar_XMLprn(TransacManager.ProtoConfig.CONFIG); try { if (!PuertoDisponible(localEndPoint.Port)) { cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKET; cxnErr.Descripcion = "Error de conexión. Puerto default ocupado."; cxnErr.Estado = 0; return cxnErr; } ipAddr = TransacManager.ProtoConfig.CONFIG.DefaultServer; ipEndPoint = new IPEndPoint(ipAddr, TransacManager.ProtoConfig.CONFIG.Port); sender = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); sender.NoDelay = false; // Using the Nagle algorithm sender.ReceiveTimeout = ProtocoloConfig.TimeoutSocket; sender.SendTimeout = ProtocoloConfig.TimeoutSocket; sender.Bind(localEndPoint); sender.Connect(ipEndPoint); } catch (Exception e) { ipHost = null; LogBMTP.LogMessage(e.Message + " \n" + e.InnerException, lvlLogDebug, TimeStampLog); } if (sender.Connected != true) { cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKET; cxnErr.Descripcion = "Error de conexión. No pudo establecerse una comunicación con los valores del PRN, ni los por defecto."; cxnErr.Estado = 0; sale = true; } else { UltimaConexionOptima[0] = TransacManager.ProtoConfig.CONFIG.DefaultServer.ToString(); UltimaConexionOptima[1] = TransacManager.ProtoConfig.CONFIG.Port.ToString(); UltimaConexionOptima[2] = TransacManager.ProtoConfig.CONFIG.Telefono; LogBMTP.LogMessage("CONEXIÓN EXITOSA CON VALORES DEFAULT:\n ", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("HOST: IP " + ipEndPoint.Address + " Port " + ipEndPoint.Port + "\n", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("BMTP: IP " + ((IPEndPoint)sender.LocalEndPoint).Address + " Port " + ((IPEndPoint)sender.LocalEndPoint).Port + "\n", lvlLogCxn, TimeStampLog); Comunicacion cm = new Comunicacion(TransacManager.ProtoConfig.BASE_CONFIG, TransacManager.ProtoConfig.CONFIG, true); cm.sender = sender; IList rdo = cm.InteraccionAB(ref ter, true); if (rdo[0] is Error) { if (((Error)rdo[0]).CodError != 0) { cxnErr = (Error)rdo; sale = true; } } else { cxnErr.CodError = (int)ErrComunicacion.CXN_NO_GENERA_PRN; cxnErr.Descripcion = "Error de conexión. No se pudo obtener el PRN."; cxnErr.Estado = 0; } fusible++; } #endregion } } else // NO EXISTE PRN { #region // INTENTA CONECTAR CON CONFIG.BIN try { if (!PuertoDisponible(TransacManager.ProtoConfig.CONFIG.Port) || !PuertoDisponible(localEndPoint.Port)) { cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKET; cxnErr.Descripcion = "Error de conexión. Puerto default ocupado."; cxnErr.Estado = 0; return cxnErr; } ipAddr = TransacManager.ProtoConfig.CONFIG.DefaultServer; ipEndPoint = new IPEndPoint(ipAddr, TransacManager.ProtoConfig.CONFIG.Port); sender = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); sender.NoDelay = false; // Using the Nagle algorithm sender.ReceiveTimeout = ProtocoloConfig.TimeoutSocket; sender.SendTimeout = ProtocoloConfig.TimeoutSocket; sender.Bind(localEndPoint); sender.Connect(ipEndPoint); //sender.Send(DataConverter.Pack("^$8", "Holaaaaaaaaa <EOF>")); } catch (Exception e) { ipHost = null; LogBMTP.LogMessage(e.Message + " \n" + e.InnerException, lvlLogDebug, TimeStampLog); } if (sender.Connected != true) { cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKET; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación con los valores por defecto."; cxnErr.Estado = 0; sale = true; } else { UltimaConexionOptima[0] = TransacManager.ProtoConfig.CONFIG.DefaultServer.ToString(); UltimaConexionOptima[1] = TransacManager.ProtoConfig.CONFIG.Port.ToString(); UltimaConexionOptima[2] = TransacManager.ProtoConfig.CONFIG.Telefono; LogBMTP.LogMessage("CONEXIÓN EXITOSA CON VALORES DEFAULT:\n ", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("HOST: IP " + ipEndPoint.Address + " Port " + ipEndPoint.Port + "\n", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("BMTP: IP " + ((IPEndPoint)sender.LocalEndPoint).Address + " Port " + ((IPEndPoint)sender.LocalEndPoint).Port + "\n", lvlLogCxn, TimeStampLog); if (TransacManager.ProtoConfig.CON_CICLO_PRN) { Comunicacion cm = new Comunicacion(TransacManager.ProtoConfig.BASE_CONFIG, TransacManager.ProtoConfig.CONFIG, true); cm.sender = sender; IList rdo = cm.InteraccionAB(ref ter, true); if (rdo[0] is Error) { if (((Error)rdo[0]).CodError != 0) { cxnErr = (Error)rdo[0]; sale = true; } } else { cxnErr.CodError = (int)ErrComunicacion.CXN_NO_GENERA_PRN; cxnErr.Descripcion = "Error de conexión. No se pudo obtener el PRN."; cxnErr.Estado = 0; } } fusible++; } #endregion if (fusible >= 2 && sale == false) { sale = true; cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKETex; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación. Se superaron los intentos de conexión."; cxnErr.Estado = 0; break; } } } #endregion if (cxnErr.CodError != 0) LogBMTP.LogMessage("Error de conexión: " + cxnErr.CodError + "\n" + " Descripción: " + cxnErr.Descripcion + "\n", lvlLogCxn, TimeStampLog); else { LogBMTP.LogMessage("CONEXIÓN EXITOSA:\n ", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("HOST: IP " + ipEndPoint.Address + " Port " + ipEndPoint.Port + "\n", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("BMTP: IP " + ((IPEndPoint)sender.LocalEndPoint).Address + " Port " + ((IPEndPoint)sender.LocalEndPoint).Port + "\n", lvlLogCxn, TimeStampLog); } return cxnErr; } catch (Exception ex) { cxnErr.CodError = (int)ErrComunicacion.CONEXIONex; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación."; cxnErr.Estado = 0; LogBMTP.LogMessage("Excepción: " + cxnErr.CodError + " " + cxnErr.Descripcion, lvlLogExcepciones, TimeStampLog); LogBMTP.LogMessage("Excepción: " + ex.ToString(), lvlLogExcepciones, TimeStampLog); return cxnErr; } }
public bool ConnectTracker() { try { if (!IsConnected) { SocketPermission permission = new SocketPermission( NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts ); permission.Demand(); IPAddress trackerAddr; if (IPAddress.TryParse(Configuration.TrackerAddress, out trackerAddr)) { byte[] buffer = new byte[1024]; lock (trackerPaddle) { IPEndPoint ipEndPoint = new IPEndPoint(trackerAddr, Configuration.Port); trackerSocket = new Socket( trackerAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); trackerSocket.NoDelay = false; trackerSocket.Connect(ipEndPoint); Message request = Message.CreateMessageHandshakePeer(); trackerSocket.Send(request.data, 0, request.data.Length, SocketFlags.None); trackerSocket.Receive(buffer, buffer.Length, SocketFlags.None); } Message response = new Message(buffer); if (response.GetMessageType() == Message.MessageType.HandshakeTracker) { int peerId; response.GetHandshakeTracker(out peerId); PeerId = peerId; IsConnected = true; Logger.WriteLine("Connection to tracker is successfully established. PeerID: " + PeerId); IPAddress ipAddr = (trackerSocket.LocalEndPoint as IPEndPoint).Address; IPEndPoint ipEndPointListener = new IPEndPoint(ipAddr, Configuration.ListenPort); SocketPermission permissionListener = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", Configuration.ListenPort); listenerSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listenerSocket.Bind(ipEndPointListener); permission.Demand(); waitPeer = new Thread(new ParameterizedThreadStart(WaitPeer)); waitPeer.Start(4); keepAlive = new Thread(new ThreadStart(SendAliveTracker)); keepAlive.Start(); return true; } else { Logger.WriteLine("Failed to connect to tracker."); return false; } } else { Logger.WriteLine("Failed to connect, tracker not found."); return false; } } else { Logger.WriteLine("Already connected to tracker."); return false; } } catch (SocketException exc) { Logger.WriteLine(exc); return false; } }
private Error Crea_PRN_Socket_TEST(Terminal ter) { //string nombre1, nombre2, nombre3, port1, port2, port3, tel1, tel2, tel3; Conexion cxn = new Conexion(); Error cxnErr = new Error(); // IPHostEntry ipHost; IPAddress ipAddr; IPAddress ipAddrLocal; try { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); ipAddrLocal = null; for (int i = 0; i < ipHostInfo.AddressList.Length; i++) { ipAddrLocal = ipHostInfo.AddressList[i]; //----------- Cambia de 1 elemento a 2. if (ipAddrLocal.AddressFamily == AddressFamily.InterNetwork) break; } IPEndPoint localEndPoint = new IPEndPoint(ipAddrLocal, TransacManager.ProtoConfig.LOCAL_PORT); SocketPermission permission = new SocketPermission(PermissionState.Unrestricted //NetworkAccess.Connect, // Connection permission //TransportType.Tcp, // Defines transport types //"", // Gets the IP addresses //SocketPermission.AllPorts // All ports ); //SocketPermissionAttribute per = new SocketPermissionAttribute(SecurityAction. permission.Demand(); #region // INTENTA CONECTAR CON CONFIG.BIN try { ipAddr = TransacManager.ProtoConfig.CONFIG.DefaultServer; ipEndPoint = new IPEndPoint(ipAddr, TransacManager.ProtoConfig.CONFIG.Port); sender = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); sender.NoDelay = false; // Using the Nagle algorithm sender.Bind(localEndPoint); sender.Connect(ipEndPoint); //sender.Send(DataConverter.Pack("^$8", "Holaaaaaaaaa <EOF>")); } catch (Exception e) { // ipHost = null; LogBMTP.LogMessage(e.Message + " \n" + e.InnerException, lvlLogDebug, TimeStampLog); } if (sender.Connected != true) { cxnErr.CodError = (int)ErrComunicacion.CXN_SOCKET; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación con los valores por defecto."; cxnErr.Estado = 0; } else { UltimaConexionOptima[0] = TransacManager.ProtoConfig.CONFIG.DefaultServer.ToString(); UltimaConexionOptima[1] = TransacManager.ProtoConfig.CONFIG.Port.ToString(); UltimaConexionOptima[2] = TransacManager.ProtoConfig.CONFIG.Telefono; LogBMTP.LogMessage("CONEXIÓN EXITOSA CON VALORES DEFAULT:\n ", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("HOST: IP " + ipEndPoint.Address + " Port " + ipEndPoint.Port + "\n", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("BMTP: IP " + ((IPEndPoint)sender.LocalEndPoint).Address + " Port " + ((IPEndPoint)sender.LocalEndPoint).Port + "\n", lvlLogCxn, TimeStampLog); } #endregion if (cxnErr.CodError != 0) LogBMTP.LogMessage("Error de conexión: " + cxnErr.CodError + "\n" + " Descripción: " + cxnErr.Descripcion + "\n", lvlLogError, TimeStampLog); else { LogBMTP.LogMessage("CONEXIÓN EXITOSA:\n ", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("HOST: IP " + ipEndPoint.Address + " Port " + ipEndPoint.Port + "\n", lvlLogCxn, TimeStampLog); LogBMTP.LogMessage("BMTP: IP " + ((IPEndPoint)sender.LocalEndPoint).Address + " Port " + ((IPEndPoint)sender.LocalEndPoint).Port + "\n", lvlLogCxn, TimeStampLog); } return cxnErr; } catch (Exception ex) { cxnErr.CodError = (int)ErrComunicacion.CONEXIONex; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación."; cxnErr.Estado = 0; LogBMTP.LogMessage("Excepción: " + cxnErr.CodError + " " + cxnErr.Descripcion, lvlLogExcepciones, TimeStampLog); LogBMTP.LogMessage("Excepción: " + ex.ToString(), lvlLogExcepciones, TimeStampLog); return cxnErr; } }
public static void Connect() { if (senderSock != null && senderSock.Connected) Disconnect(); GameNotification.GetInstance().PushMessage("Connecting"); try { // Create one SocketPermission for socket access restrictions var permission = new SocketPermission( NetworkAccess.Connect, // Connection permission TransportType.Tcp, // Defines transport types "", // Gets the IP addresses SocketPermission.AllPorts // All ports ); // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance var ipHost = Dns.GetHostEntry(Consts.SERVER_IP); // Gets first IP address associated with a localhost var ipAddr = IPAddress.Parse("192.168.56.1"); //ipHost.AddressList[3]; // Creates a network endpoint IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Consts.PORT); // Create one Socket object to setup Tcp connection senderSock = new Socket( ipAddr.AddressFamily,// Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); // Establishes a connection to a remote host for (int attemp = 0; attemp < Consts.MAX_CONNECTION_ATTEMPTS && !senderSock.Connected; attemp++) { try { senderSock.Connect(ipEndPoint); break; } catch { } } if (senderSock.Connected) { GameNotification.GetInstance().PushMessage("Connected"); // Update player turn SendMessage(new Message { Name = myName, RoomId = roomId, Turn = -1 }); var message = ReceiveMessage(); if (message.Turn >= 0) { turn = message.Turn; opName = message.Name; mapId = message.Col; } else { Disconnect(); } } else GameNotification.GetInstance().PushMessage("Cant connect"); } catch (Exception e) { GameNotification.GetInstance().PushMessage("Cant connect"); } }
/* This method is invoked when the 'Connect' button is clicked. * It connects the client to the server asynchronously. */ private void Connect_Click(object sender, RoutedEventArgs e) { // The code is written in try block so as to catch any exceptions, if thrown try { // Create one SocketPermission for socket access restrictions SocketPermission permission = new SocketPermission( NetworkAccess.Connect, // Connection permission TransportType.Tcp, // Defines transport types "", // Gets the IP addresses SocketPermission.AllPorts // All ports ); // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry(""); // Gets first IP address associated with a localhost IPAddress ipAddr = ipHost.AddressList[0]; // Creates a network endpoint IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510); // Create one Socket object to setup Tcp connection senderSock = new Socket( ipAddr.AddressFamily, // Specifies the addressing scheme SocketType.Stream, // The type of socket ProtocolType.Tcp // Specifies the protocols ); // Establishes a connection to a remote host senderSock.Connect(ipEndPoint); // Disabling the 'Connect' button Connect_Button.IsEnabled = false; // Enabling the 'Send' button Send_Button.IsEnabled = true; } // Used for catching any exceptions, if thrown catch (Exception exc) { MessageBox.Show(exc.ToString()); } }
//************* public methods ************************* /// <devdoc> /// <para>Associates a socket with an end point.</para> /// </devdoc> public void Bind(EndPoint localEP) { if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Bind", localEP); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // // parameter validation // if (localEP==null) { throw new ArgumentNullException("localEP"); } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() localEP:" + localEP.ToString()); EndPoint endPointSnapshot = localEP; IPEndPoint ipSnapshot = localEP as IPEndPoint; // // for now security is implemented only on IPEndPoint // If EndPoint is of other type - unmanaged code permisison is demanded // if (ipSnapshot != null) { // Take a snapshot that will make it immutable and not derived. ipSnapshot = ipSnapshot.Snapshot(); // DualMode: Do the security check on the users IPv4 address, but map to IPv6 before binding. endPointSnapshot = RemapIPEndPoint(ipSnapshot); // // create the permissions the user would need for the call // SocketPermission socketPermission = new SocketPermission( NetworkAccess.Accept, Transport, ipSnapshot.Address.ToString(), ipSnapshot.Port); // // demand for them // socketPermission.Demand(); // Here the permission check has succeded. // NB: if local port is 0, then winsock will assign some>1024, // so assuming that this is safe. We will not check the // NetworkAccess.Accept permissions in Receive. } else { //< ExceptionHelper.UnmanagedPermission.Demand(); } // // ask the EndPoint to generate a SocketAddress that we // can pass down to winsock // SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPointSnapshot); DoBind(endPointSnapshot, socketAddress); if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Bind", ""); }
/// <summary> /// Connect to the given IP (port 9993) and return the socket. /// </summary> /// <param name="ip"></param> /// <returns>a socket connection to the given IP</returns> private Socket ConnectServer(string ip) { Socket socket = null; try { SocketPermission permission = new SocketPermission( NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts ); // Ensures permission to access the socket permission.Demand(); IPAddress ipAddr = IPAddress.Parse( ip ); //IPEndPoint ipEndPoint = new IPEndPoint( ipAddr, 9993 ); // Create one Socket object to setup Tcp connection socket = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); socket.NoDelay = false; // Establishes a connection to a remote host, timeout in 1 second (plenty of time in this day & age). IAsyncResult result = socket.BeginConnect( ipAddr, 9993, null, null ); bool success = result.AsyncWaitHandle.WaitOne( 1000, true ); if ( !success ) { // CLOSE THE SOCKET! socket.Close(); Output( string.Format( "unable to connect to {0}", ip ) ); return null; } // connect to a remote host //socket.Connect( ipEndPoint ); Output( string.Format( "connected to {0}", socket.RemoteEndPoint ) ); ReceiveDataFromServer( socket ); } catch ( Exception exc ) { MessageBox.Show( exc.ToString() ); } return socket; }