public ClientNetwork(Game ngame, string ip, int port) { Hello msg = new Hello(); SendReceiveOptions customSendReceiveOptions = new SendReceiveOptions <ProtobufSerializer>(); con = TCPConnection.GetConnection(new ConnectionInfo(ip, port), customSendReceiveOptions); NetworkComms.AppendGlobalIncomingPacketHandler <Back>("Back", processBack); NetworkComms.AppendGlobalIncomingPacketHandler <Msg>("Msg", processMsg); NetworkComms.AppendGlobalIncomingPacketHandler <InitMsg>("InitMsg", processInitMsg); NetworkComms.AppendGlobalIncomingPacketHandler <GameCommand>("GameCommand", processGC); game = ngame; msg.text = game.getName(); try { con.SendObject("Hello", msg); } catch (ArgumentException) { Console.WriteLine("Couldn't send request message. It appears to be an internal error. too bad :/"); } catch (ConnectionSetupException) { Console.WriteLine("Couldn't send request message. Maybe the ip address is wrong or the server isn't running?"); } catch (CommunicationException) { Console.WriteLine("Couldn't send request message. Maybe the ip address is wrong or the server isn't running?"); } game.setCon(con); }
public Connection ConnectToServer() { ConnectionInfo connInfo = new ConnectionInfo(IpAddress, IpPort); Connection newTCPConn = TCPConnection.GetConnection(connInfo); return(newTCPConn); }
/// <summary> /// Try to connect to the server/host /// </summary> /// <param name="connectionInfo">The IP and port to try to connect to</param> public static void ConnectToServer(ConnectionInfo connectionInfo) { Connection connection; //Try to connect to the server using TCP try { connection = TCPConnection.GetConnection(connectionInfo); } //Catch any connection error and send an error message catch { MDI_Container.staticMdi_Container.mdi_Join.Invoke(MDI_Forms.MDI_Join.DJoinResult, new object[] { false }); return; } //Add a event handler to handle a shutdown of the connection connection.AppendShutdownHandler(new NetworkComms.ConnectionEstablishShutdownDelegate((c) => MDI_Container.staticMdi_Container.BeginInvoke(MDI_Container.staticMdi_Container.DLostConnection))); //Register incoming packet handler for setting up RPC from the server NetworkComms.AppendGlobalIncomingPacketHandler <string>("Initialize-Connection", InitializeServerRPC); //Set the RPC server to use the newly established connection with the server RemoteProcedureCalls.Server.serverConnection = connection; //Register a instance of the clients interface and make it available to the server via RPC RemoteProcedureCalls.Server.RegisterInstanceForPublicRemoteCall <ClientInterfaceClass, IClientInterface>(new ClientInterfaceClass(), "Client"); //Send a command to the server to tell it to connect to the clients RPC connection.SendObject <string>("Initialize-Connection", ""); }
private void sendMsg() { if (textBox1.Text.Length == 0) { return; } if (isHost == true) { messageHolder toSend = new messageHolder(host.name + ": " + textBox1.Text); ChatLog.Items.Add(host.name + ": " + textBox1.Text); List <ConnectionInfo> l = NetworkComms.AllConnectionInfo(); foreach (ConnectionInfo i in l) { TCPConnection.GetConnection(i).SendObject("Message", toSend); } } else { messageHolder toSend = new messageHolder(cinfo.name + ": " + textBox1.Text); ChatLog.Items.Add(cinfo.name + ": " + textBox1.Text); newTCPConn.SendObject("Message", toSend); } textBox1.Clear(); }
/// <summary> /// Establishes a connection to the server using the cached port number /// </summary> /// <returns>TCPConnection object for client-server communication</returns> TCPConnection ConnectUsingCache() { int serverPort = GetCachedPort(); ConnectionInfo connInfo = new ConnectionInfo(IPAddress.Loopback.ToString(), serverPort); return(TCPConnection.GetConnection(connInfo)); }
protected void ReceiveSessionVerification(PacketHeader header, Connection connection, string session) { long id = accountRepository.GetSessionAccountId(session); if (id == -1) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(PacketName.ReSessionVerificationResult.ToString(), GenericResponse.Fail); } else { lock (authorizedAccounts) { if (authorizedAccounts.ContainsKey(connection.ConnectionInfo.NetworkIdentifier)) { authorizedAccounts[connection.ConnectionInfo.NetworkIdentifier] = id; } else { authorizedAccounts.Add(connection.ConnectionInfo.NetworkIdentifier, id); } } TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(PacketName.ReSessionVerificationResult.ToString(), GenericResponse.Success); } }
protected void ReceiveRequestServiceLog(PacketHeader header, Connection connection, ServiceLogRequest request) { // ######################################################################## // This method requires authentication. // If user is not authorized then send UnAuthorized and end method. if (!accountManager.Authorized(connection)) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReUnauthorized.ToString(), 1); return; } // ######################################################################## List <ServiceLog> logs = serviceManager.RetrieveLogs(request.id, request.dateLimit); if (logs.Count > 0) { List <ServiceLogItem> serviceLogItems = new List <ServiceLogItem>(); foreach (ServiceLog log in logs) { serviceLogItems.Add(new ServiceLogItem(log.id, log.serviceId, log.text, log.date)); } ServiceLogList serviceLogList = new ServiceLogList(serviceLogItems.ToArray()); TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( Networking.Data.PacketName.ReServiceLog.ToString(), serviceLogList); } }
protected void ReceiveRequestAllAppList(PacketHeader header, Connection connection, int code) { // ######################################################################## // This method requires authentication. // If user is not authorized then send UnAuthorized and end method. if (!accountManager.Authorized(connection)) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReUnauthorized.ToString(), 1); return; } // ######################################################################## long accountId = accountManager.AuthorizedAccountId(connection); if (accountId != -1) { List <ModuleInfo> moduleInfoList = new List <ModuleInfo>(); foreach (Module service in moduleRepository.RetrieveApps()) { moduleInfoList.Add(new ModuleInfo(service.id, service.type, service.name, service.version, service.path, service.enabled)); } ModuleList moduleList = new ModuleList(moduleInfoList.ToArray()); TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( Networking.Data.PacketName.ReAllAppList.ToString(), moduleList); } }
//固定的返回匹配字符串 private void button1_Click(object sender, EventArgs e) { //连接信息 var connInfo = new ConnectionInfo(txtSerIP.Text, int.Parse(txtSerPort.Text)); try { //连接服务器 var newTcpConnection = TCPConnection.GetConnection(connInfo); bool ConFlag = newTcpConnection.ConnectionAlive(1000); if (!newTcpConnection.ConnectionAlive(1000) || newTcpConnection == null) { this.txtReInfo.Text = "未找到服务端..."; } //发送【GetName】请求,获取对应【ResName】值 string resMsg = newTcpConnection.SendReceiveObject <string, string>("GetName", "ResName", 5000, listBox1.Text); this.txtReInfo.Text = resMsg; } catch (Exception ex) { throw; } ////5秒重联 //var retryForever =Policy.Handle<Exception>() // .WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(5), (exception, timespan) => { // Console.WriteLine(exception.Message); // }); //retryForever.Execute(() => { // //重连方法? //}); }
static void Main(string[] args) { Connection _socket = null; if (args.Length != 2) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("./Server.exe [IP SERVER] [PORT]"); Console.ForegroundColor = ConsoleColor.White; return; } string serverIP = args[0]; int serverPort = int.Parse(args[1]); try{ _socket = TCPConnection.GetConnection(new ConnectionInfo(serverIP, serverPort)); _socket.AppendIncomingPacketHandler <ServerRequest>("ServerRequest", IncomingServerRequest); _socket.AppendIncomingPacketHandler <ClientRequest>("ServerRequest", IncomingClientRequest); _socket.AppendShutdownHandler(connectionDown); game = new GameClient(_socket); }catch (NetworkCommsDotNet.ConnectionSetupException exp) { Console.WriteLine("Invlide IP or Port, please check"); return; } lock (game) { Monitor.Wait(game); } }
private void CheckPeersOnline() { if (peers != null) { foreach (Peer peer in peers.peers_list) { ConnectionInfo connInfo = new ConnectionInfo(peer.ip_address, serverPort); if (peer.ip_address != CurrentIPAddress() && peer.ip_address != "127.0.0.1") { try { peer.conn = TCPConnection.GetConnection(connInfo, true); if (peer.conn.ConnectionAlive(100)) { peer.last_seen = DateTime.UtcNow; peer.connected = true; } } catch (Exception ex) { Console.WriteLine(ex); peer.connected = false; } } else { peer.connected = true; peer.last_seen = DateTime.UtcNow; } } } connectedPeers = CountPeersOnline(); }
protected void ReceiveRequestAppFile(PacketHeader header, Connection connection, long moduleId) { // ######################################################################## // This method requires authentication. // If user is not authorized then send UnAuthorized and end method. if (!accountManager.Authorized(connection)) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReUnauthorized.ToString(), 1); return; } // ######################################################################## Module module = moduleRepository.Get(moduleId); string filePath = module.path; byte[] fileData = File.ReadAllBytes(filePath); AppFileData appData = new AppFileData(module.id, filePath, fileData); TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReAppFile.ToString(), appData); }
//获取所有在线用户的信息 private void GetP2PInfo() { IList <UserIDEndPoint> userInfoList = Common.TcpConn.SendReceiveObject <IList <UserIDEndPoint> >("GetP2PInfo", "ResP2pInfo", 5000, "GetP2P"); foreach (UserIDEndPoint userInfo in userInfoList) { try { if (userInfo.UserID != Common.CurrentUser.ID) { ConnectionInfo connInfo = new ConnectionInfo(userInfo.IPAddress, userInfo.Port); Connection newTcpConnection = TCPConnection.GetConnection(connInfo); Common.AddUserConn(userInfo.UserID, newTcpConnection); SetUpP2PContract contract = new SetUpP2PContract(); contract.UserID = Common.CurrentUser.ID; //P2p通道打通后,发送一个消息给对方用户,以便于对方用户收到消息后,建立P2P通道 newTcpConnection.SendObject("SetupP2PMessage", contract); } } catch { } } }
protected void RequestAccountList(PacketHeader header, Connection connection, int code) { // ######################################################################## // This method requires authentication. // If user is not authorized then send UnAuthorized and end method. if (!Authorized(connection)) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReUnauthorized.ToString(), 1); return; } // ######################################################################## if (Administrator(connection)) { List <Account> sendAccounts = new List <Account>(); List <Repository.Entities.Account> accounts = accountRepository.GetAll(); foreach (Repository.Entities.Account account in accounts) { sendAccounts.Add(new Account(account.id, account.username, account.firstname, account.lastname)); } TCPConnection.GetConnection(connection.ConnectionInfo). SendObject(PacketName.ReAccountList.ToString(), sendAccounts.ToArray()); } }
private static void SendToServer <T>(string sendMessage, T objectToSend) where T : ServerObject { ConnectionInfo serverConnectionInfo; if (ip == null) { return; } try { serverConnectionInfo = new ConnectionInfo(ip, CommonInfo.ServerPort); } catch (Exception e) { Console.WriteLine(e.ToString()); //ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again"); return; } try { TCPConnection serverConnection = TCPConnection.GetConnection(serverConnectionInfo); serverConnection.SendObject(sendMessage, objectToSend.SerializeToString()); } catch (CommsException e) { Console.WriteLine(e.ToString()); /*AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again.");*/ } catch (Exception e) { Console.WriteLine(e.ToString()); /*AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again.");*/ } }
protected void ReceiveRequestGroupList(PacketHeader header, Connection connection, int code) { // ######################################################################## // This method requires authentication. // If user is not authorized then send UnAuthorized and end method. if (!Authorized(connection)) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReUnauthorized.ToString(), 1); return; } // ######################################################################## if (Administrator(connection)) { List <Group> sendUserGroups = new List <Group>(); List <Repository.Entities.Group> userGroupAccess = groupRepository.RetrieveAll(); foreach (Repository.Entities.Group access in userGroupAccess) { sendUserGroups.Add(new Group(access.id, access.name, access.description)); } TCPConnection.GetConnection(connection.ConnectionInfo). SendObject(PacketName.ReUserGroupList.ToString(), new GroupList(sendUserGroups.ToArray())); } }
public static bool StartClient(string Hostname, int Port, string Password) { try { logger.Info("Trying to connect to Server"); _Password = Password; isServer = false; IPAddress ipAddress = null; try { ipAddress = IPAddress.Parse(Hostname); } catch (FormatException) { // Improperly formed IP address. // Try resolving as a domain. ipAddress = Dns.GetHostEntry(Hostname).AddressList[0]; } ConnectionInfo serverInfo = new ConnectionInfo(ipAddress.ToString(), Port); NetworkComms.AppendGlobalConnectionEstablishHandler(HandleNewConnection, false); NetworkComms.AppendGlobalIncomingPacketHandler <iRTVOMessage>("iRTVOMessage", HandleIncomingMessage); NetworkComms.AppendGlobalIncomingPacketHandler <object>("iRTVOAuthenticate", HandleAuthenticateRequest); NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed); TCPConnection.GetConnection(serverInfo, true); } catch (Exception ex) { logger.Error("Failed to connect to Server: {0}", ex.Message); return(false); } return(true); }
// Methods #region FileSend void FileSend() { //This is our progress percent, between 0 and 1 double progressPercentage = 0; //Initialise stream with 1MB byte[] buffer = new byte[1024 * 1024]; ThreadSafeStream dataToSend = new ThreadSafeStream(new System.IO.MemoryStream(buffer)); long totalBytesSent = 0; //We will send in chunks of 50KB int sendInChunksOfNBytes = 50 * 1024; //Get the connection to the target Connection connection = TCPConnection.GetConnection(new ConnectionInfo(this.serverIp, this.serverPort)); do { //Determine the total number of bytes to send //We need to watch out for the end of the buffer when we send less than sendInChunksOfNBytes long bytesToSend = (buffer.Length - totalBytesSent > sendInChunksOfNBytes ? sendInChunksOfNBytes : buffer.Length - totalBytesSent); StreamSendWrapper streamWrapper = new StreamSendWrapper(dataToSend, totalBytesSent, bytesToSend); connection.SendObject("PartitionedSend", streamWrapper); totalBytesSent += bytesToSend; progressPercentage = ((double)totalBytesSent / buffer.Length); }while (totalBytesSent < buffer.Length); }
public void TestMethodNetworkAndTracker() { VotingsUser.Trackers = CommonHelpers.GetLocalEndPoint(CommonHelpers.TrackerPort, true).Address.ToString(); VotingsUser.PeerDiscovery = false; //создаем трекер var tr = new BlockChainVotingsTracker.Tracker(); tr.Start(); //добавляем пир в трекер var con = TCPConnection.GetConnection(new ConnectionInfo(CommonHelpers.GetLocalEndPoint(10000, true)), false); var peer = new BlockChainVotingsTracker.Peer(con, tr.Peers, new System.Timers.Timer()); peer.Status = BlockChainVotingsTracker.PeerStatus.Connected; tr.Peers.Add(peer); //создаем клиент и подключаемся var net = new Network(); net.Connect(); w(); w(); Assert.IsTrue(net.Started == true); Assert.IsTrue(net.Trackers.Count == 1); Assert.IsTrue(net.Peers.Count == 1); //отключаемся net.Disconnect(); w(); Assert.IsTrue(net.Started == false); Assert.IsTrue(net.Trackers.Count == 0); Assert.IsTrue(net.Peers.Count == 0); }
public static void RemoteExecute(this Node to, string code) { if (Node.This == to) { throw new InvalidOperationException("Can't send data to self."); } TCPConnection.GetConnection(new ConnectionInfo(to.IP, Ports.DiscoveryPort)).Execute(code); }
private static void TellClientToUpdateUsers(UserInfo userInfo) { string serializedUser = userInfo.SerializeToString(); foreach (ConnectionInfo info in NetworkComms.AllConnectionInfo()) { TCPConnection.GetConnection(info).SendObject(Messages.UserUpdated, serializedUser); } }
static void Main(string[] args) { string messageToSend = "This is the message to send"; TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000)).SendObject("Message", messageToSend); Console.WriteLine("Press any key to exit client."); Console.ReadKey(true); NetworkComms.Shutdown(); }
private static void TellClientToRemoveSneeze(SneezeRecord sneeze) { string serializedSneeze = sneeze.SerializeToString(); foreach (ConnectionInfo info in NetworkComms.AllConnectionInfo()) { TCPConnection.GetConnection(info).SendObject(Messages.SneezeRemoved, serializedSneeze); } }
public void Send(Guid guid, PacketData packetData) { List <Connection> connections = NetworkComms.GetExistingConnection(guid, ConnectionType.TCP); foreach (Connection connection in connections) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject("Custom", packetData.ToPacket()); } }
public NetworkManager(string serverIp, int serverPort, User user) { NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEtablished); NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed); addPacketHandlers(); ServerPort = serverPort; _user = user; ServerIp = serverIp; Server = TCPConnection.GetConnection(new ConnectionInfo(ServerIp, ServerPort)); }
/// <summary> /// Send our message. /// </summary> private void SendMessage() { //If we have tried to send a zero length string we just return if (messageText.Text.Trim() == "") { return; } //We may or may not have entered some server connection information ConnectionInfo serverConnectionInfo = null; if (serverIP.Text != "") { try { serverConnectionInfo = new ConnectionInfo(serverIP.Text.Trim(), int.Parse(serverPort.Text)); } catch (Exception) { MessageBox.Show("Failed to parse the server IP and port. Please ensure it is correct and try again", "Server IP & Port Parse Error", MessageBoxButton.OK); return; } } //We wrap everything we want to send in the ChatMessage class we created ChatMessage messageToSend = new ChatMessage(NetworkComms.NetworkIdentifier, localName.Text, messageText.Text, messageSendIndex++); //We add our own message to the message history in-case it gets relayed back to us lock (lastPeerMessageDict) lastPeerMessageDict[NetworkComms.NetworkIdentifier] = messageToSend; //We write our own message to the chatBox AppendLineToChatBox(messageToSend.SourceName + " - " + messageToSend.Message); //We refresh the MessagesFrom box so that it includes our own name RefreshMessagesFromBox(); //We clear the text within the messageText box. this.messageText.Text = ""; //If we provided server information we send to the server first if (serverConnectionInfo != null) { //We perform the send within a try catch to ensure the application continues to run if there is a problem. try { TCPConnection.GetConnection(serverConnectionInfo).SendObject("ChatMessage", messageToSend); } catch (CommsException) { MessageBox.Show("A CommsException occurred while trying to send message to " + serverConnectionInfo, "CommsException", MessageBoxButton.OK); } } //If we have any other connections we now send the message to those as well //This ensures that if we are the server everyone who is connected to us gets our message var otherConnectionInfos = (from current in NetworkComms.AllConnectionInfo() where current != serverConnectionInfo select current).ToArray(); foreach (ConnectionInfo info in otherConnectionInfos) { //We perform the send within a try catch to ensure the application continues to run if there is a problem. try { TCPConnection.GetConnection(info).SendObject("ChatMessage", messageToSend); } catch (CommsException) { MessageBox.Show("A CommsException occurred while trying to send message to " + info, "CommsException", MessageBoxButton.OK); } } }
protected void ReceiveRequestUserAppList(PacketHeader header, Connection connection, int code) { // ######################################################################## // This method requires authentication. // If user is not authorized then send UnAuthorized and end method. if (!accountManager.Authorized(connection)) { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( PacketName.ReUnauthorized.ToString(), 1); return; } // ######################################################################## long accountId = accountManager.AuthorizedAccountId(connection); if (accountId != -1) { List <ModuleInfo> moduleInfoList = new List <ModuleInfo>(); List <Repository.Entities.Group> userGroupAccess = groupRepository.RetrieveAccountAccess(accountId); foreach (Module service in moduleRepository.RetrieveEnabledApps()) { List <Repository.Entities.Group> appGroupAccess = groupRepository.RetrieveAppAccess(service.id); bool foundGroupInCommon = false; foreach (Repository.Entities.Group appGroup in appGroupAccess) { // One of the groups in appGroupAccess needs to exist in userGroupAccess. foreach (Repository.Entities.Group userGroup in userGroupAccess) { if (appGroup.id == userGroup.id) { foundGroupInCommon = true; break; } } } if (foundGroupInCommon) { moduleInfoList.Add(new ModuleInfo(service.id, service.type, service.name, service.version, service.path, service.enabled)); } } // groupRepository ModuleList moduleList = new ModuleList(moduleInfoList.ToArray()); TCPConnection.GetConnection(connection.ConnectionInfo).SendObject( Networking.Data.PacketName.ReModuleList.ToString(), moduleList); } }
public void SendPacket(Connection connection, string packetType, object packetData) { try { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject(packetType, packetData); } catch { HandleConnectionClosed(connection); } }
public void Send(PacketData packetData) { try { TCPConnection.GetConnection(connectionInfo).SendObject("Custom", packetData.ToPacket()); } catch { InvokeDisconnect(); } }
public void Send(string name, object obj) { try { TCPConnection.GetConnection(connectionInfo).SendObject(name, obj); } catch { InvokeDisconnect(); } }