public Player(TcpClient client, string ip, byte id) { try { this.username = "******"; this.plyClient = client; this.x = 0; this.y = 0; this.z = 0; this.rotx = 0; this.roty = 0; this.prefix = ""; this.id = id; this.ip = ip; this.world = null; this.outQueue = new Queue<Packet>(); this.blockQueue = new Queue<Packet>(); this.IOThread = new Thread(PlayerIO); this.outputWriter = new BinaryWriter(client.GetStream()); this.inputReader = new BinaryReader(client.GetStream()); this.IOThread.IsBackground = true; this.IOThread.Start(); } catch { } }
public static string ListFiles() { using (TcpClient socket = new TcpClient()) { string total = null; socket.Connect(IPAddress.Loopback, PORT); StreamWriter output = new StreamWriter(socket.GetStream()); // Send request type line output.WriteLine("LIST_FILES"); // Send message end mark and flush it output.WriteLine(); output.Flush(); // Read response string line; StreamReader input = new StreamReader(socket.GetStream()); while ((line = input.ReadLine()) != null && line != string.Empty) total += line + "/n"; output.Close(); socket.Close(); return total; } }
public void Connect(IPEndPoint remoteAddress) { BaseSocket = new TcpClient(); BaseSocket.Connect(remoteAddress); OutputStream = new StreamWriter(new BufferedStream(BaseSocket.GetStream())); InputStream = new StreamReader(new BufferedStream(BaseSocket.GetStream())); }
public Boolean Connect(String ip, int port) { try { TcpClient = new System.Net.Sockets.TcpClient(); TcpClient.ReceiveTimeout = 5000; TcpClient.SendTimeout = 5000; TcpClient.Connect(ip, port); Ns = TcpClient.GetStream(); Bw = new BinaryWriter(TcpClient.GetStream()); Br = new BinaryReader(TcpClient.GetStream()); IsConnected = true; } catch (Exception e) { IsConnected = false; Log.Cl(e.Message); return false; } ReceptionThread = new Thread(new ThreadStart(Run)); ReceptionThread.IsBackground = true; ReceptionThread.Start(); return true; }
public string Execute(string command) { try { Log.InfoFormat("Executing command {0} @{1}:{2}", command, HostName, Port); var client = new TcpClient(HostName, Port); var commandBytes = ASCIIEncoding.ASCII.GetBytes(command); client.GetStream().Write(commandBytes, 0, commandBytes.Length); var buffer = new byte[MAX_BUFFER_LENGTH]; var readLen = client.GetStream().Read(buffer, 0, buffer.Length); var result = ASCIIEncoding.ASCII.GetString(buffer.Take(readLen).ToArray()); client.Close(); return result; } catch (Exception ex) { Log.Error(ex.Message, ex); throw; } }
public Form1() { InitializeComponent(); client = new TcpClient("127.0.0.1",8888); r = new StreamReader(client.GetStream()); w = new StreamWriter(client.GetStream()); }
internal static string OpenConnection() { errorMsg = string.Empty; _dataBuffer = string.Empty; int result = 0; int.TryParse(ConfigurationSupport.currentPort, out result); try { _client = new TcpClient(ConfigurationSupport.currentHost, result); string str = QuickRead(null); if (str != ConfigurationSupport.version) { errorMsg = errorMsg + "Mismatched versions." + Environment.NewLine; errorMsg = errorMsg + string.Format("SERVER: ({0})" + Environment.NewLine, str); errorMsg = errorMsg + string.Format("CLIENT: ({0})" + Environment.NewLine, ConfigurationSupport.version); CloseConnection(); } if (_client.Connected) { StreamWriter writer = new StreamWriter(_client.GetStream()); writer.WriteLine(string.Format("VersionInfo {{{0}}}", ConfigurationSupport.version)); writer.Flush(); _sslStreamReader = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallBack)); try { _sslStreamReader.AuthenticateAsClient(ConfigurationSupport.currentHost, null, SslProtocols.Ssl3, false); } catch (AuthenticationException exception) { errorMsg = errorMsg + "SSL Authentication Error." + Environment.NewLine; errorMsg = errorMsg + exception.ToString(); } _sslStreamWriter = new StreamWriter(_sslStreamReader); _sslStreamWriter.AutoFlush = true; _sslStreamWriter.WriteLine(string.Format("ValidateUser {0} {1}", ConfigurationSupport.currentUsername, ConfigurationSupport.currentPassword)); string str2 = QuickRead(_sslStreamReader); if (str2 == "UserID INVALID") { CloseConnection(); errorMsg = "Invalid USERNAME and/or PASSWORD"; } else { isConnected = true; ConfigurationSupport.userID = str2.Split(new char[0])[1]; } } } catch (Exception ex) { isConnected = false; errorMsg = string.Format("Could not connect to {0}:{1}", ConfigurationSupport.currentHost, ConfigurationSupport.currentPort); } if (isConnected) { _readBuffer = new byte[0x100]; _sslStreamReader.BeginRead(_readBuffer, 0, _readBuffer.Length, new AsyncCallback(SguildConnection.OnReceivedData), _client.GetStream()); } return errorMsg; }
public void TestListen() { try { Identd.Start("username"); Thread.Sleep( 1000 ); TcpClient client = new TcpClient(); client.Connect("localhost", 113); StreamWriter writer = new StreamWriter( client.GetStream() ); writer.WriteLine( "a query" ); writer.Flush(); StreamReader reader = new StreamReader( client.GetStream() ); string line = reader.ReadLine(); Identd.Stop(); Assertion.AssertEquals( "a query : USERID : UNIX : username", line.Trim() ); } catch( Exception e ) { Assertion.Fail("IO Exception during test:" + e); } }
public async Task HandleClientAsync(TcpClient c) { string msg = null; bool connected = true; Console.WriteLine($"Connection accepted {DateTime.Now.ToShortTimeString()}"); using (var output = new StreamWriter(c.GetStream(), UTF32Encoding.ASCII) { AutoFlush = true }) { using (var input = new StreamReader(c.GetStream(), UTF32Encoding.ASCII)) { while (connected) { switch (msg = await input.ReadLineAsync()) { case "done": connected = false; break; default: await output.WriteLineAsync(msg); break; } } } } c.Close(); Console.WriteLine("bye..."); }
static void Main(string[] args) { TcpClient cl = new TcpClient(); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000); cl.Connect(iep); Console.WriteLine("Connected to Server!!!"); //NetworkStream ns = new NetworkStream(); StreamReader sr = new StreamReader(cl.GetStream()); StreamWriter sw = new StreamWriter(cl.GetStream()); string st = sr.ReadLine(); Console.WriteLine("Server:{0}",st); while (true) { //string st; Console.Write("Nhap du lieu gui len Server:"); st = Console.ReadLine(); sw.WriteLine(st); sw.Flush(); if (st.ToUpper().Equals("QUIT")) break; st = sr.ReadLine(); Console.WriteLine("Data From Server:{0}", st); } sw.Close(); sr.Close(); cl.Close(); //ns.Close(); }
public string GetCompletion(string[] args) { if (args == null || haxeProcess == null) return string.Empty; if (!IsRunning()) StartServer(); try { var client = new TcpClient("127.0.0.1", port); var writer = new StreamWriter(client.GetStream()); writer.WriteLine("--cwd " + (PluginBase.CurrentProject as HaxeProject).Directory); foreach (var arg in args) writer.WriteLine(arg); writer.Write("\0"); writer.Flush(); var reader = new StreamReader(client.GetStream()); var lines = reader.ReadToEnd(); client.Close(); return lines; } catch(Exception ex) { TraceManager.AddAsync(ex.Message); if (!failure && FallbackNeeded != null) FallbackNeeded(false); failure = true; return string.Empty; } }
//method: UserConnectionToServer //description: initializes a new user connection to the server //params: Control owner - owner // string server - server // int port - port // string userName - user's name/username //returns: void //throws ArgumentException and SocketException and IOException public UserConnectionToServer(Control owner, string server, int port, string userName) { this.owner = owner; //get name userName = userName.Trim(); if(userName == "") { throw new ArgumentException("Name cannot be blank.", "userName"); } //try to connect socket = new TcpClient(server, port); reader = new LinePeekableReader(new StreamReader(socket.GetStream())); writer = new StreamWriter(socket.GetStream()); //identify as a user and provide name writer.WriteLine("user"); writer.WriteLine(userName); writer.Flush(); //start reading from server Thread thread = new Thread(ConnectionReader); thread.IsBackground = true; thread.Start(); }
public void Init(TcpClient tcpclient, int maxPackSize = 2048) { if (!tcpclient.Connected) throw new Exception("Must be connected"); _tcpClient = tcpclient; base.Init(tcpclient.GetStream(), tcpclient.GetStream(), maxPackSize); }
public override bool Initialize() { Logger.Log($"Connecting to Twitch IRC -> {Account.Username}"); _Client = new TcpClient(); _Client.ConnectAsync("irc.twitch.tv", 6667).Wait(); _Writer = new StreamWriter(_Client.GetStream()); _Reader = new StreamReader(_Client.GetStream()); Logger.Log("Sending login credentials"); _SendStringRaw($"PASS {Account.OAuth}"); _SendStringRaw($"NICK {Account.Username}"); var response = IRCMessage.Parse(_Reader.ReadLine()); if (response.Type != "001") { Logger.Log("Server did not return expected login message"); return false; } // runners new Thread(_SendRunner).Start(); new Thread(_ReceiveRunner).Start(); Logger.Log("Connecting to channels"); foreach (var c in Channels) _SendString($"JOIN #{c}", MessagePriority.Medium); return true; }
private void ConnectButton_Click(object sender, EventArgs e) { if ((tcpClient == null) || (!tcpClient.Connected)) { tcpClient = new TcpClient(); try { MessageLabel.Text = "Connecting..."; Application.DoEvents(); tcpClient.Connect(TransportHostTextBox.Text, (int)TransportPortNumericUpDown.Value); streamWriter = new StreamWriter(tcpClient.GetStream()); streamWriter.AutoFlush = true; streamReader = new StreamReader(tcpClient.GetStream()); backgroundWorker.RunWorkerAsync(); ConnectButton.Text = "Dis&connect"; MessageLabel.Text = "Connected"; TransportHostTextBox.Enabled = false; TransportPortNumericUpDown.Enabled = false; JabberIDTextBox.Enabled = false; Authenticated = false; skypeProxy.Command("GET CURRENTUSERHANDLE"); } catch (SocketException ex) { MessageLabel.Text = ex.Message; tcpClient = null; } } else { backgroundWorker_RunWorkerCompleted(sender, null); } }
public string connect() { //Initialize to the pop server. This code snipped "borrowed" //with some modifications... //from the article "Retrieve Mail From a POP3 Server Using C#" at //www.codeproject.com by Agus Kurniawan //http://www.codeproject.com/csharp/popapp.asp // create server with port 110 Server = new TcpClient(pop,110); try { // initialization NetStrm = Server.GetStream(); RdStrm= new StreamReader(Server.GetStream()); //The pop session is now in the AUTHORIZATION state state=connect_state.AUTHORIZATION ; return(RdStrm.ReadLine ()); } catch(InvalidOperationException err) { return("Error: "+err.ToString()); } }
public void Connect(IPEndPoint endPoint, bool secure, bool rogue) { _connection = new TcpClient(); _connection.Connect(endPoint); if (secure) { if (rogue) { _stream = _connection.GetStream(); SendGarbage(); } else { var sslStream = new SslStream(_connection.GetStream(), false, (p1, p2, p3, p4) => true); sslStream.AuthenticateAsClient( "localhost", null, SslProtocols.Tls, false ); _stream = sslStream; } } }
private static void StopIBController() { // Stop IBController if it's still running. IBController listens on a port // for three commands: STOP, EXIT, and ENABLEAPI. Here we send a STOP, then // an EXIT to cleanly shutdown TWS. try { byte[] stop = Encoding.Default.GetBytes("STOP\n"); byte[] exit = Encoding.Default.GetBytes("EXIT\n"); // connect to the IBController socket TcpClient tcp = new TcpClient(Settings.Default.IBControllerIp, Settings.Default.IBControllerPort); // send the "STOP" byte array to the IBController socket tcp.GetStream().Write(stop, 0, stop.Length); // send the "EXIT" command tcp.GetStream().Write(exit, 0, exit.Length); } catch (SocketException sockEx) { StringBuilder builder = new StringBuilder(); builder.AppendFormat("IBController socket exeception: {0}\n", sockEx.Message); builder.AppendLine("Check the IP setting in IBController.ini,"); builder.AppendLine("ensure it matches the setting in IBControllerService.config."); Logger.Instance.WriteError(builder.ToString()); if (sockEx.InnerException != null) Logger.Instance.WriteError("Inner Exception: {0}", sockEx.InnerException.Message); } catch (Exception ex) { Logger.Instance.WriteError(ex.Message); } }
public StreamingAPIConnect(StreamingListener sl, string ip, int port, LoginResponse lr, bool secure) { this.sl = sl; this.streamingSessionId = lr.StreamingSessionId; apiSocket = new System.Net.Sockets.TcpClient(ip, port); if (secure) { SslStream ssl = new SslStream(apiSocket.GetStream()); ssl.AuthenticateAsClient("xtb.com"); //hardcoded domain, because we use ip-version of the address apiWriteStream = new StreamWriter(ssl); apiBufferedReader = new StreamReader(ssl); } else { NetworkStream ns = apiSocket.GetStream(); apiWriteStream = new StreamWriter(ns); apiBufferedReader = new StreamReader(ns); } Thread t = new Thread(delegate() { while (running) { readStreamMessage(); Thread.Sleep(50); } }); t.Start(); //System.Threading.Timer t = new System.Threading.Timer(o => readStreamMessage(), null, 0, 10); }
public TcpConnection(TcpClient socket) { if (socket == null) throw new ArgumentNullException("socket"); _socket = socket; _inputStream = new StreamReader(socket.GetStream()); _outputStream = new StreamWriter(socket.GetStream()); }
private void button1_Click(object sender, EventArgs e) { try { endereco_ip = IPAddress.Parse("127.0.0.2"); servidor = new TcpClient(); servidor.Connect(endereco_ip, 2502); conectado = true; enviador = new StreamWriter(servidor.GetStream()); enviador.WriteLine("3"); enviador.Flush(); enviador = new StreamWriter(servidor.GetStream()); enviador.Write(NomeUsuario); enviador.Flush(); enviador = new StreamWriter(servidor.GetStream()); enviador.WriteLine(txt_senha.Text); enviador.Flush(); comunicacao = new Thread(new ThreadStart(RespostaServidor)); comunicacao.Start(); status.Text = "Conectado"; } catch (Exception erro) { MessageBox.Show(erro.Message.ToString(), "Erro", MessageBoxButtons.OK); } }
public GameClient(TcpClient selfClient, Guid onlineId, IClientKiller killer, ChatManager manager, GameLoop game) { _self = selfClient; _self.NoDelay = true; _self.Client.NoDelay = true; _reader = new BinaryReader(_self.GetStream()); _writer = new BinaryWriter(_self.GetStream()); _clientKiller = killer; _game = game; ChatManager chatManager = manager; chatManager.Join(this); _auth = AuthorisationManager.Resolve(); _packetReader = PacketReader.Resolve<ServerPacketReader>(); _packetReader.InitialiseMapping(); OnlineId = onlineId; _active = true; _subs = new List<PacketSubscriber> { this, _game, chatManager }; Task.Factory.StartNew(Receive); }
public RemoteProcessClient(string host, int port) { client = new TcpClient(host, port) {SendBufferSize = BufferSizeBytes, ReceiveBufferSize = BufferSizeBytes}; reader = new BinaryReader(client.GetStream()); writer = new BinaryWriter(client.GetStream()); }
public Session( World _world, TcpClient _client ) { world = _world; loginTime = DateTime.Now; canReceive = true; canQueue = true; canSend = false; canDispose = false; outputQueue = new Queue<Packet>(); priorityOutputQueue = new Queue<Packet>(); queueLock = new object(); priorityQueueLock = new object(); client = _client; client.SendTimeout = 10000; client.ReceiveTimeout = 10000; reader = new BinaryReader( client.GetStream() ); writer = new PacketWriter( new BinaryWriter( client.GetStream() ) ); world.log.Log( "Session: {0}", LogType.Debug, ToString() ); ioThread = new Thread( IoLoop ); ioThread.IsBackground = true; ioThread.Start(); }
private void Connect() { try { client = new TcpClient(); client.Connect("localhost", 1992); using (StreamReader reader = new StreamReader(client.GetStream(), Encoding.ASCII)) { writer = new StreamWriter(client.GetStream(), Encoding.ASCII); connected = true; OnConnected(); string line; while ((line = reader.ReadLine()) != null) { OnData(JObject.Parse(line)); } } } catch (Exception e) { Logger.Error("Socket", "Thread crashed: " + e.ToString()); client.Close(); connected = false; OnDisconnected(); Logger.Verbose("Socket", "Waiting before trying reconnect."); Util.RunLater(() => { Connect(); }, "Reconnect", TimeSpan.FromSeconds(30)); } }
/// <summary> /// Retrieves whois information /// </summary> /// <param name="domainName">The registrar or domain or name server whose whois information to be retrieved</param> /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param> /// <returns></returns> public static string Lookup(string domainName, RecordType recordType) { string whoisServerName = WhoisServerResolver.GetWhoisServerName(domainName); using (TcpClient whoisClient = new TcpClient()) { whoisClient.Connect(whoisServerName, Whois_Server_Default_PortNumber); string domainQuery = recordType.ToString() + " " + domainName + "\r\n"; byte[] domainQueryBytes = Encoding.ASCII.GetBytes(domainQuery.ToCharArray()); Stream whoisStream = whoisClient.GetStream(); whoisStream.Write(domainQueryBytes, 0, domainQueryBytes.Length); StreamReader whoisStreamReader = new StreamReader(whoisClient.GetStream(), Encoding.ASCII); string streamOutputContent = ""; List<string> whoisData = new List<string>(); while (null != (streamOutputContent = whoisStreamReader.ReadLine())) { whoisData.Add(streamOutputContent); } whoisClient.Close(); return String.Join(Environment.NewLine, whoisData); } }
private void SendAsync( ) { TcpClient client = new TcpClient( Peer.EndPoint.AddressFamily ); try { client.SendTimeout = 30; client.Connect( Peer.EndPoint ); using ( BinaryReader NetworkInStream = new BinaryReader( client.GetStream( ) ) ) using ( BinaryWriter NetworkOutStream = new BinaryWriter( client.GetStream( ) ) ) { bool sendPeers = Peer.ShouldSendPeers; var header = new Header( sendPeers ); NetworkOutStream.Write( header.ToString( ) ); NetworkOutStream.Flush( ); // Update the statistics. Peer.RegisterEvent( PeerStatistics.EventType.SentInfo ); if ( sendPeers ) { log.InfoFormat( "Sent {0} peers to {1}", PeerList.Peers.Count, Peer ); Peer.RegisterEvent( PeerStatistics.EventType.SentPeerList ); } } } catch ( SocketException e ) { log.Info( "Error during outgoing who's-there: " + e ); } catch ( IOException e ) { log.Info( "Error during outgoing who's-there: " + e ); } }
void SendTcpMethod(string[] args) { //Check for correct amount of arguments if (args.Length != 2) throw new ArgumentException("Parameters: <Destination> <Port>"); string server = args[0]; int servPort = Int32.Parse(args[1]); //Create a socket that is connected to a server on a specifed port TcpClient client = new TcpClient(server, servPort); NetworkStream netStream = client.GetStream(); //Make an item to quote ItemQuote quote = new ItemQuote(12345678909876554L, "5mm Super Widgets", 1000, 1299, true, false); //Send text-encoded quote ItemQuoteEncoderText coder = new ItemQuoteEncoderText(); byte[] codedQuote = coder.encode(quote); Console.WriteLine("Sening text-encoded quote (" + codedQuote.Length + " bytes): "); Console.WriteLine(quote); netStream.Write(codedQuote, 0, codedQuote.Length); //Receive binary-encoded quote ItemQuoteDecoder decoder = new ItemQuoteDecoderBin(); ItemQuote receivedQuote = decoder.decode(client.GetStream()); Console.WriteLine("Reveived Binary-Encode Quote:"); Console.WriteLine(receivedQuote); }
private static void ListLocations(string fileName) { using (TcpClient socket = new TcpClient()) { socket.Connect(IPAddress.Loopback, PORT); StreamWriter output = new StreamWriter(socket.GetStream()); // Send request type line output.WriteLine("LIST_LOCATIONS"); // Send message payload output.WriteLine(fileName); // Send message end mark and flush it output.WriteLine(); output.Flush(); // Read response string line; StreamReader input = new StreamReader(socket.GetStream()); while ((line = input.ReadLine()) != null && line != string.Empty) Console.WriteLine(line); output.Close(); socket.Close(); } }
public ServerConnection(string host, int port, string username, string password) { Host = host; Port = port; Username = username; _currentConnection = this; try { Client = new TcpClient(host, port); Reader = new StreamReader(Client.GetStream()); Writer = new StreamWriter(Client.GetStream()); if (password.Equals("")) { Writer.WriteLine("M:/name " + username); } else { Writer.WriteLine("M:/auth " + username + " " + password); } Writer.Flush(); Writer.WriteLine("S:Client"); Writer.Flush(); Writer.WriteLine("S:Account"); Writer.Flush(); Writer.WriteLine("S:ChannelClientList"); Writer.Flush(); } catch { Client = null; } }
private void Listen() { try { bool done = false; TcpListen = new System.Net.Sockets.TcpListener(6811); Debug.Log(TcpListen); TcpListen.Start(); System.Net.Sockets.TcpClient client = TcpListen.AcceptTcpClient(); Debug.Log(client); if (client != null) { m_NetworkStream = client.GetStream(); System.Net.Sockets.NetworkStream ns = m_NetworkStream; //listen Receive StartReceiveData(); while (!done) { if (ns != null) { continue; //pause one test/**/ Debug.Log(ns); //CWritePacket packet = new CWritePacket((int)D2CMessage.EBuilding_Update); //packet.WriteInt(345); //packet.WriteString("keyinishihuaihaizi"); //packet.WriteShort(15); //packet.WriteByte(10); try { //ns.Write( packet.GetPacketByte(), 0, packet.GetPacketLen() ); //ns.Close(); //client.Close(); } catch (System.Exception ex) { Debug.Log("listen error!" + ex.Message); } } } } } catch (System.Exception ex) { Debug.Log("listen error111!" + ex.Message); } }
private void CallBackBeginReceive(System.IAsyncResult ar) { try { var bytes = this.tcpClient.GetStream().EndRead(ar); if (bytes == 0) { Disconnect(); return; } var recievedMessage = Encoding.UTF8.GetString(buffer, 0, bytes); Debug.Log(recievedMessage); var m = MessageData.FromJson(recievedMessage); _messageData.OnNext(m); tcpClient.GetStream().BeginRead(buffer, 0, buffer.Length, CallBackBeginReceive, null); } catch (System.Exception e) { Disconnect(); } }
private void ConnectUnity(string host, string port) { #if !UNITY_EDITOR errorStatus = "Unity TCP client used in UWP!"; #else System.Net.IPAddress MyMSIipAddress; System.Net.IPAddress ServerAddress; try { if (exchangeThread != null) { StopExchange(); } //if (GameSettings.Instance == null) { OTHERipAddress = System.Net.IPAddress.Parse("192.168.1.3"); } //else //{ // OTHERipAddress = System.Net.IPAddress.Parse(GameSettings.Instance.My_Partner_IP); //} int portint = Int32.Parse(port); MyMSIipAddress = System.Net.IPAddress.Parse("192.168.1.2"); ServerAddress = System.Net.IPAddress.Parse("192.168.1.3"); System.Net.IPEndPoint ipLocalEndPoint = new System.Net.IPEndPoint(MyMSIipAddress, portint); // TcpClient clientSocket = new TcpClient(ipLocalEndPoint); // clientSocket.Connect(remoteHost, remotePort); // client = new System.Net.Sockets.TcpClient(host, Int32.Parse(port)); client = new System.Net.Sockets.TcpClient(ipLocalEndPoint); client.Connect(ServerAddress, 50111); TrackingManager.DisplayReceivedMessage("yo connecting to port" + port); stream = client.GetStream(); reader = new StreamReader(stream); writer = new StreamWriter(stream) { AutoFlush = true }; RestartExchange(); successStatus = "Connected!"; } catch (Exception e) { errorStatus = e.ToString(); } #endif }
private void ConnectToServer() { try { string[] ss = server.Split(':'); tcp = new System.Net.Sockets.TcpClient(ss [0], int.Parse(ss [1])); //NetworkStreamを取得する ns = tcp.GetStream(); // masks = new byte[(int)(Mathf.Ceil (modules.Length / 7f))]; // buf = new byte[modules.Length * 5]; } catch (Exception e) { print(e); return; } isConnectedToServer = true; }
public async System.Threading.Tasks.Task <string> Connect(string ip_addr, string port) { connectSocket = new System.Net.Sockets.TcpClient(); try { await connectSocket.ConnectAsync(ip_addr, Int32.Parse(port)); } catch (Exception ex) { _canConnect = false; Debug.Log(ex); throw new Exception("Server not found at: " + ip_addr); } streamOut = connectSocket.GetStream(); writer = new StreamWriter(streamOut); reader = new StreamReader(streamOut); _connected = true; return(null); }
public DateTime GetOnlineDate() { DateTime OnlineDate; var client = new System.Net.Sockets.TcpClient("time.nist.gov", 13); if (CheckForInternetConnection()) { using (var streamReader = new System.IO.StreamReader(client.GetStream())) { var response = streamReader.ReadToEnd(); var utcDateTimeString = response.Substring(7, 17); OnlineDate = DateTime.ParseExact(utcDateTimeString, "yy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal); } return(OnlineDate); } else { return(DateTime.Now); } }
//Connect using the Unity codebase private void ConnectUnity(string host, int port) { #if !UNITY_EDITOR Debug.Log("Unity TCP client used in UWP!"); #else try { //Setup the connection client = new System.Net.Sockets.TcpClient(host, port); //Start recieving server information on a sepparete thread client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoReadUnity), null); Debug.Log("Connection Succeeded"); } catch (Exception ex) { Debug.Log("Connection failed" + ex + "\n"); } #endif }
private static byte[] sendMessage(byte[] messageBytes) { const int bytesize = 1024 * 1024; try // Try connecting and send the message bytes { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient("127.0.0.1", 1234); // Create a new connection NetworkStream stream = client.GetStream(); stream.Write(messageBytes, 0, messageBytes.Length); // Write the bytes messageBytes = new byte[bytesize]; // Clear the message // Clean up stream.Dispose(); client.Close(); } catch (Exception e) // Catch exceptions { MessageBox.Show(e.Message); } return(messageBytes); // Return response }
private void sendMessage(string deviceName, string command, int value) { NetworkStream serverStream = sock.GetStream(); //calculate actual value to pass to motor. value of 64 is stop, > 64 is forward, < 64 is backwards. range is 0-128 value = (value * ((addValue) ? 1 : -1)) + 64; byte[] outStream = System.Text.Encoding.ASCII.GetBytes(deviceName + ", " + command + ", " + value + ":!"); string sendData = System.Text.Encoding.ASCII.GetString(outStream); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); //TODO: have this recieve command back //TODO: after recieving, compare to sent message to check for transmission errors //TODO: implement timeout on recieving to ensure connection isnt lost //read back buffer. We were getting issues, so commented out for now byte[] inStream = new byte[99999]; serverStream.Read(inStream, 0, (int)sock.ReceiveBufferSize); string returnData = System.Text.Encoding.ASCII.GetString(inStream); lblDisplay.Text = returnData; }
public void StartIRC() { System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient(); sock.Connect(server, port); if (!sock.Connected) { Debug.Log("Failed to connect!"); return; } var networkStream = sock.GetStream(); var input = new System.IO.StreamReader(networkStream); var output = new System.IO.StreamWriter(networkStream); if (genericIRC) { // output.WriteLine("PASS " + password); output.WriteLine("NICK " + nickName.ToLower()); output.Flush(); string USER = "******" + nickName + " 0 * :" + nickName; output.WriteLine(USER); output.Flush(); } else { //Send PASS & NICK. output.WriteLine("PASS " + oauth); output.WriteLine("NICK " + nickName.ToLower()); output.Flush(); } //output proc outProc = new System.Threading.Thread(() => IRCOutputProcedure(output)); outProc.Start(); //input proc inProc = new System.Threading.Thread(() => IRCInputProcedure(input, networkStream)); inProc.Start(); }
public MyStatus(System.Net.Sockets.TcpClient clientSocket_, Form parent_) { InitializeComponent(); parent = parent_; string myStatusMsg = "225"; NetworkStream serverStream = clientSocket_.GetStream(); byte[] outStream = System.Text.Encoding.ASCII.GetBytes(myStatusMsg); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); byte[] inStream = new byte[3 + 4]; //3 bytes of msg code and 4 bytes of number of games serverStream.Read(inStream, 0, 7); string returndata = System.Text.Encoding.ASCII.GetString(inStream); // 126 0000 000000 000000 0000 // code games right wrong avg int numOfgames = int.Parse(returndata.Substring(3, 4)); if (numOfgames != 0) { inStream = new byte[6 + 6 + 4]; serverStream.Read(inStream, 0, 16); returndata = System.Text.Encoding.ASCII.GetString(inStream); numOfGames.Text += numOfgames; numOfRightAns.Text += int.Parse(returndata.Substring(0, 6)).ToString(); numOfWrongAns.Text += int.Parse(returndata.Substring(6, 6)).ToString(); AvgTimeForAns.Text += float.Parse(returndata.Substring(12, 2) + "." + returndata.Substring(14, 2)).ToString(); } else { numOfGames.Text += "0"; numOfRightAns.Text += "0"; numOfWrongAns.Text += "0"; AvgTimeForAns.Text += "0"; } }
byte[] readBytes; // receieve data buffer /** * @brief TcpClientStart * @param[in] string ipAddStr ServerIPAddress * @param[in] int portno PortNo * @param[in] string sndStr 送信文字列 * @return void * @note TcpClient接続、コマンド送信、受信待ち開始 */ bool TcpClientStart(string ipAddStr, int portno, string sndStr) { try { readBytes = new byte[512]; // TcpClinet でコマンド送信 tcpClient = new System.Net.Sockets.TcpClient(ipAddStr, portno); ntstrm = tcpClient.GetStream(); // コマンドを Byte型に変換 sndStr = sndStr + "\r\n"; byte[] sendBytes = Encoding.ASCII.GetBytes(sndStr); // コマンド送信 ntstrm.Write(sendBytes, 0, sendBytes.Length); // Ack/Nack 受信待ち。 callback Method登録 ntstrm.BeginRead(readBytes, 0, readBytes.Length, new AsyncCallback(RecvCallback), null); return(true); } catch (System.Net.Sockets.SocketException skerr) { if (ntstrm != null) { ntstrm.Close(); ntstrm = null; } if (tcpClient != null) { tcpClient.Close(); tcpClient = null; } skerr.ToString(); return(false); } }
//受信開始ボタン private void button3_Click(object sender, EventArgs e) { try { tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); tcp.NoDelay = true; label8.Text = "Client:" + ipOrHost + " :" + port; ns = tcp.GetStream(); ns.ReadTimeout = Timeout.Infinite; ns.WriteTimeout = Timeout.Infinite; enc = System.Text.Encoding.UTF8; tcpflag = true; TcpReadThread = new Thread(TcpRead); TcpReadThread.IsBackground = true; TcpReadThread.Priority = System.Threading.ThreadPriority.Normal; TcpReadThread.Start(); MotionThread = new Thread(TcpFunc); MotionThread.IsBackground = true; MotionThread.Priority = System.Threading.ThreadPriority.Normal; MotionThread.Start(); } catch (Exception err) { MessageBox.Show(err.Message); } textBox7.Enabled = true; groupBox2.Enabled = true; //タイマーの作成 boringTimer.Interval = 1000; boringTimer.Tick += new EventHandler(timer_tick); }
private async void InitListener() { var tcpServer = new Sockets.TcpListener(IPAddress.Any, ClientListenerPort); tcpServer.Start(); while (true) { tcpReciever = await tcpServer.AcceptTcpClientAsync(); var stream = tcpReciever.GetStream(); properlyDisconnected = false; while (true) { var message = TcpUtils.ReadMessage(stream); if (string.IsNullOrEmpty(message)) { if (!properlyDisconnected) { Invoke(new Action(() => { MessageBox.Show(this, "Соединение с сервером потеряно. Подключение будет закрыто", "Сервер отключен", MessageBoxButtons.OK, MessageBoxIcon.Information); Disconnect(); })); } break; } message = DateTime.Now.ToString("t") + ": " + message; lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message))); } } }
// Update is called once per frame void Update() { // Server should receive a message from the client NetworkStream networkStream = clientSocket.GetStream(); byte[] bytesFrom = new byte[100000]; networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize); dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom); dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\n")); char[] delimiterChars = { ' ', ',', '\n' }; coordinates = dataFromClient.Split(delimiterChars); //ToDo - Socket info from the Barrett Arm double xx = Convert.ToDouble(coordinates[0]); double yy = Convert.ToDouble(coordinates[1]); double zz = Convert.ToDouble(coordinates[2]); /* * Before tranformations * Barrett.x = (float) yy * 10; * Barrett.y = (float) zz * 10; * Barrett.z = (float) xx * (-10); */ Barrett.x = (float)xx * (-10); Barrett.y = (float)zz * 10; Barrett.z = (float)yy * (-10); transform.position = Barrett; if (Barrett.x < 10 && Barrett.x > -10 && Barrett.x < 10 && Barrett.x > -10 && Barrett.z < 0 && Barrett.z > -10) { //sw.WriteLine(Barrett.x + ", " + Barrett.y + ", " + Barrett.z); } depthPlane.transform.position = new Vector3(0, 0, transform.position.z); }
public static void Main() { try { var i = 0; var client = new System.Net.Sockets.TcpClient(); client.Connect(Dns.GetHostName(), 2055); var stream = client.GetStream(); while (i < 3) { const string message = "client1 "; var data = System.Text.Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); data = new byte[256]; var bytes = stream.Read(data, 0, data.Length); var responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); i++; } stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.WriteLine("\n Press Enter to continue..."); Console.ReadLine(); }
public static void Main(string[] args) { Console.WriteLine("Client Started"); try { clientSocket.Connect("127.0.0.1", 8888); NetworkStream serverStream = clientSocket.GetStream(); byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$"); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); do { byte[] inStream = new byte[1024]; serverStream.Read(inStream, 0, inStream.Length); string returndata = System.Text.Encoding.ASCII.GetString(inStream); Console.WriteLine("Data from Server : " + returndata); } while (serverStream.DataAvailable); } catch (Exception e) { Console.WriteLine("{0}", e.Message); } }
/// <summary> /// Establish the TCP connection /// </summary> /// <param name="keepalive">Wether the connection should be kept alive after a first message</param> /// <returns>True for success, False otherwise</returns> public override bool Connect(bool keepalive = true) { try { // connect socket connection = new System.Net.Sockets.TcpClient(); connection.ReceiveTimeout = 2000; connection.Connect(EndPoint); System.IO.Stream connectionStream = connection.GetStream(); Stream = new IpcStream(connectionStream, KnownTypes, Encryptor); } catch (SocketException e) { System.Diagnostics.Debug.WriteLine(e); return(false); } if (keepalive) { StartPing(); } return(true); }
public string SendAndReceive(string message) { lock (_dataLockObject) { if (_dataClient == null) { _dataClient = new System.Net.Sockets.TcpClient(); _dataClient.Connect(_host, _dataPort); _dataStream = OnPrepareStream(_dataClient.GetStream()); } message = PrepareOutgoingMessage(message); var success = TcpProtocolHelper.Write(_dataStream, message); if (!success) { return(null); } return(PrepareIncommingMessage(TcpProtocolHelper.Read(_dataStream))); } }
public async Task ConnectAsync(CancellationToken cancellationToken = default(CancellationToken)) { try { //Connect async method await Close(); cancellationToken.ThrowIfCancellationRequested(); _client = new System.Net.Sockets.TcpClient(); cancellationToken.ThrowIfCancellationRequested(); await _client.ConnectAsync(_server, _port); await CloseIfCanceled(cancellationToken); // get stream and do SSL handshake if applicable _stream = _client.GetStream(); await CloseIfCanceled(cancellationToken); } catch (Exception e) { CloseIfCanceled(cancellationToken).Wait(); throw; } }
public void SendData(string filename) { //string filename = @"C:\temp\torrent\files\Lynda Python Essential Training\01. Introduction\01_01-Welcome.mp4"; byte[] fileBytes = System.IO.File.ReadAllBytes(filename); Console.WriteLine(fileBytes.Length); //return; NetworkStream serverStream = clientSocket.GetStream(); //byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$"); //serverStream.Write(outStream, 0, outStream.Length); serverStream.Write(BitConverter.GetBytes(fileBytes.Length), 0, 4); serverStream.Write(fileBytes, 0, fileBytes.Length); //serverStream.Flush(); byte[] inStream = new byte[1024]; serverStream.Read(inStream, 0, 1024); string returndata = System.Text.Encoding.ASCII.GetString(inStream); msg("Data from Server : " + returndata); }
private void beginTradingToolStripMenuItem_Click(object sender, EventArgs e) { // Create three stocks and add them to the market Subject = new RealTimedata(); // In this lab assignment we will add three companies only using the following format: // Company symbol , Company name , Open price Subject.addCompany("MSFT", "Microsoft Corporation", 46.13); Subject.addCompany("AAPL", "Apple Inc.", 105.22); Subject.addCompany("FB", "Facebook, Inc.", 80.67); this.watchToolStripMenuItem.Visible = true; this.ordersToolStripMenuItem.Visible = true; this.beginTradingToolStripMenuItem.Enabled = false; this.marketToolStripMenuItem.Text = "&Join <<Connected>>"; clientSocket.Connect(txtServerIP.Text, Convert.ToInt32(txtServerPort.Text)); System.Net.Sockets.NetworkStream netStream = clientSocket.GetStream(); Byte[] sendRegister = Encoding.UTF8.GetBytes("REGISTER/" + txtUsername.Text + "/" + txtClientIP.Text + "/" + txtClientPort.Text); netStream.Write(sendRegister, 0, sendRegister.Length); MarketDepthSubMenu(this.marketByOrderToolStripMenuItem1); MarketDepthSubMenu(this.marketByPriceToolStripMenuItem1); }
private void Run() { Task.Run(async() => { try { using (_remoteClient) using (client) { await client.ConnectAsync(_remoteServer.Address, _remoteServer.Port); var serverStream = client.GetStream(); var remoteStream = _remoteClient.GetStream(); await Task.WhenAny(remoteStream.CopyToAsync(serverStream), serverStream.CopyToAsync(remoteStream)); } } catch (Exception) { } finally { Console.WriteLine($"Closed {_clientEndpoint} => {_remoteServer}"); _remoteClient = null; } }); }
private void button1_Click(object sender, EventArgs e) {// these codes are sending arithmatic expression only one time to server NetworkStream netStream = clientSocket.GetStream(); byte[] outp = System.Text.Encoding.ASCII.GetBytes(tmsgtoserver.Text + "$"); netStream.Write(outp, 0, outp.Length); netStream.Flush(); byte[] inp = new byte[20000]; string returndata = System.Text.Encoding.ASCII.GetString(inp); tmsgtoserver.Text = ""; tmsgtoserver.Focus(); //these codes are for retrieving answer from server byte[] bytes = new byte[clientSocket.ReceiveBufferSize]; // Read can return anything from 0 to numBytesToRead. netStream.Read(bytes, 0, (int)clientSocket.ReceiveBufferSize); // Returns the data received from the host to the console. string dat = System.Text.Encoding.UTF8.GetString(bytes); lans.Text = dat; }
public void connectToBot() { clientSocket = new System.Net.Sockets.TcpClient(); log.logMsg(log.messages[0], log.normalColor); try { clientSocket.Connect(BotIP, BotPort); stream = clientSocket.GetStream(); } catch (SocketException e) { log.logMsg(log.messages[3], log.warningColor); // Debug.Log(e.Message); connectedFalse(); } if (clientSocket != null && clientSocket.Connected) { mjpeg.streamAddress = "http://" + BotIP + ":" + BotCameraPort.ToString() + "/stream.mjpg"; connectedTrue(); log.logMsg(log.messages[1], log.normalColor); log.inputKeyboardSelected(); } }
public void ServerThreadProc() { while (true) { try { // 處理用戶端連線 tcpClient = tcpListener.AcceptTcpClient(); // 取得本機相關的網路資訊 IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint; // 以Client屬性取得用戶端之Socket物件 Socket clientSocket = tcpClient.Client; // 取得連線用戶端相關的網路連線資訊 IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint; Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString()); Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString()); // 取得伺服端的輸出入串流 NetworkStream networkStream = tcpClient.GetStream(); // 判斷串流是否支援讀取功能 if (networkStream.CanRead) { byte[] bytes = new byte[1024]; int bytesReceived = 0; string data = null; do { // 自資料串流中讀取資料 bytesReceived = networkStream.Read(bytes, 0, bytes.Length); data += Encoding.ASCII.GetString(bytes, 0, bytesReceived); } while (networkStream.DataAvailable); // 判斷串流中的資料是否可供讀取 Console.WriteLine("接收的資料內容: " + "\r\n" + "{0}", data + "\r\n"); } else { Console.WriteLine("串流不支援讀取功能."); } // 判斷串流是否支援寫入功能 if (networkStream.CanWrite) { // 測試用 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); // 將資料寫入資料串流中 networkStream.Write(msg, 0, msg.Length); Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", Encoding.UTF8.GetString(msg, 0, msg.Length) + "\r\n"); } else { Console.WriteLine("串流不支援寫入功能."); } // 關閉串流 networkStream.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); } } }
/// <summary> /// Establish a connection to the server. /// </summary> public void Connect() { if (IsConnected) { Logger?.Invoke(_Header + "already connected"); return; } else { Logger?.Invoke(_Header + "initializing client"); InitializeClient(_Ssl, _PfxCertFilename, _PfxPassword); Logger?.Invoke(_Header + "connecting to " + ServerIpPort); } _TokenSource = new CancellationTokenSource(); _Token = _TokenSource.Token; IAsyncResult ar = _Client.BeginConnect(_ServerIp, _ServerPort, null, null); WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(_Settings.ConnectTimeoutMs), false)) { _Client.Close(); throw new TimeoutException("Timeout connecting to " + ServerIpPort); } _Client.EndConnect(ar); _NetworkStream = _Client.GetStream(); if (_Ssl) { if (_Settings.AcceptInvalidCertificates) { _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate)); } else { _SslStream = new SslStream(_NetworkStream, false); } _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates); if (!_SslStream.IsEncrypted) { throw new AuthenticationException("Stream is not encrypted"); } if (!_SslStream.IsAuthenticated) { throw new AuthenticationException("Stream is not authenticated"); } if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated) { throw new AuthenticationException("Mutual authentication failed"); } } if (_Keepalive.EnableTcpKeepAlives) { EnableKeepalives(); } } catch (Exception) { throw; } finally { wh.Close(); } _IsConnected = true; _LastActivity = DateTime.Now; _IsTimeout = false; _Events.HandleConnected(this, new ClientConnectedEventArgs(ServerIpPort)); _DataReceiver = Task.Run(() => DataReceiver(_Token), _Token); _IdleServerMonitor = Task.Run(() => IdleServerMonitor(), _Token); }
static public void Run() { Console.WriteLine("IP:"); string ipStr = Console.ReadLine(); IPAddress ip; if (!IPAddress.TryParse(ipStr, out ip)) { Console.WriteLine("IP地址[{0}]无效。", ipStr); return; } Console.WriteLine("Port:"); string portStr = Console.ReadLine(); ushort port; if (!ushort.TryParse(portStr, out port)) { Console.WriteLine("端口[{0}]无效。", portStr); return; } IPEndPoint endPoint = new IPEndPoint(ip, port); System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(AddressFamily.InterNetwork); try { Console.WriteLine("正在连接[{0}:{1}]...", ip, port); tcpClient.Connect(endPoint); } catch (SocketException se) { Console.WriteLine("连接失败:" + se.SocketErrorCode.ToString()); return; } catch (Exception e) { Console.WriteLine("连接失败:" + e.Message); return; } NetworkStream ns = null; while (true) { if (ns == null) { ns = tcpClient.GetStream(); } Console.WriteLine("请输入信息:"); string msg = Console.ReadLine(); byte[] msgByte = System.Text.Encoding.UTF8.GetBytes(msg); byte[] msgByte_send = new byte[msgByte.Length + 1]; for (int i = 0; i < msgByte.Length; i++) { msgByte_send[i] = msgByte[i]; } msgByte_send[msgByte_send.Length - 1] = 0; try { //ns = tcpClient.GetStream(); ns.Write(msgByte_send, 0, msgByte_send.Length); ns.Flush(); } catch (SocketException se) { Console.WriteLine("发送消息失败:" + se.SocketErrorCode.ToString()); return; } catch (Exception e) { Console.WriteLine("发送消息失败:" + e.Message); return; } Console.WriteLine(""); Console.WriteLine("正在等待接收信息..."); byte[] recMsgByte = new byte[4096]; int recLen; try { //ns = tcpClient.GetStream(); recLen = ns.Read(recMsgByte, 0, recMsgByte.Length); } catch (SocketException se) { Console.WriteLine("接收消息失败:" + se.SocketErrorCode.ToString()); return; } catch (Exception e) { Console.WriteLine("接收消息失败:" + e.Message); return; } string recMsg = System.Text.Encoding.UTF8.GetString(recMsgByte, 0, recLen); Console.WriteLine(recMsg); Console.WriteLine(""); //int int32 = BitConverter.ToInt32(recMsgByte, 0); //string hexStr = "0x" + Convert.ToString(int32, 16); //Console.WriteLine(hexStr); if (Console.KeyAvailable) { break; } } }
private void SignIn_Click(object sender, EventArgs e) { try { if (userNameBox.Text.Length == 0 || passwordBox.Text.Length == 0) { msgToUser.Text = "Please fill all fields"; msgToUser.Visible = true; return; } string signInMsg = "200" + userNameBox.Text.Length.ToString().PadLeft(2, '0') + userNameBox.Text + passwordBox.Text.Length.ToString().PadLeft(2, '0') + passwordBox.Text; NetworkStream serverStream = clientSocket.GetStream(); byte[] outStream = System.Text.Encoding.ASCII.GetBytes(signInMsg); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); byte[] inStream = new byte[4]; serverStream.Read(inStream, 0, 4); string returndata = System.Text.Encoding.ASCII.GetString(inStream); //msg(returndata); switch (returndata.Substring(0, 4)) { case "1020": //Success Sign_up_outB.Text = "Sign out"; UserNameLable.Hide(); PasswordLable.Hide(); userNameBox.Hide(); passwordBox.Hide(); SignIn.Hide(); GreetingsLable.Text = "Hello " + userNameBox.Text; GreetingsLable.Visible = true; TriviaLogoTop.Image = Properties.Resources.Trivia; TriviaLogoRight.Image = Properties.Resources.Trivia; TriviaLogoLeft.Image = Properties.Resources.Trivia; JoinRoom.Enabled = true; CreateRoom.Enabled = true; MyStatus.Enabled = true; BestScores.Enabled = true; JoinRoom.Show(); CreateRoom.Show(); MyStatus.Show(); BestScores.Show(); msgToUser.Text = ""; msgToUser.Visible = false; break; case "1021": //Wrong Details msgToUser.Text = "Wrong Details"; msgToUser.Visible = true; //set trivia to red TriviaLogoTop.Image = Properties.Resources.ErrorTriviaLogo; TriviaLogoRight.Image = Properties.Resources.ErrorTriviaLogo; TriviaLogoLeft.Image = Properties.Resources.ErrorTriviaLogo; break; case "1022": //User is already connected msgToUser.Text = "User is already connected"; msgToUser.Visible = true; //set trivia to red TriviaLogoTop.Image = Properties.Resources.ErrorTriviaLogo; TriviaLogoRight.Image = Properties.Resources.ErrorTriviaLogo; TriviaLogoLeft.Image = Properties.Resources.ErrorTriviaLogo; break; default: msg("Got unknown code: " + returndata); break; } } catch (Exception exc) { msg(exc.Message); } }
private void bt_login_Click(object sender, EventArgs e) { //byte[] bytes = new byte[1024]; username = txt_username.Text; MessageBox.Show(username); //binding socket // eplocal = new IPEndPoint(IPAddress.Parse(SR_IP), Convert.ToInt32("12000")); //skt.Bind(eplocal); /* * try * { * epremote = new IPEndPoint(IPAddress.Parse("10.0.0.2"), Convert.ToInt32("12000")); * //skt.Connect("10.0.0.2",12000); * skt.Connect(epremote); * byte[] msg = Encoding.ASCII.GetBytes("Login"); * skt.Send(msg); * byte[] msg1 = Encoding.ASCII.GetBytes(txt_username.Text); * skt.Send(msg1); * byte[] msg2 = Encoding.ASCII.GetBytes(txt_passwd.Text); * skt.Send(msg2); * * buffer = new byte[1500]; * skt.Receive(buffer); * string returndata = System.Text.Encoding.ASCII.GetString(buffer); * MessageBox.Show(returndata); * } * catch (Exception e1) * { * MessageBox.Show("ArgumentNullException : {0}", e1.ToString()); * }*/ /*// start * 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 = ipHostInfo.AddressList[0]; * //IPEndPoint remoteEP = new IPEndPoint('10.0.0.2', 12000); * * // Create a TCP/IP socket. * * // Connect the socket to the remote endpoint. Catch any errors. * try * { * sender.Connect("10.0.0.2", 12000); * * // Console.WriteLine("Socket connected to {0}", * // new Socket(AddressFamily.InterNetwork, * //SocketType.Stream, ProtocolType.Tcp).RemoteEndPoint.ToString()); * * // Encode the data string into a byte array. * byte[] msg = Encoding.ASCII.GetBytes("Login"); * * // Send the data through the socket. * int bytesSent = sender.Send(msg); * * msg = Encoding.ASCII.GetBytes(txt_username.Text); * bytesSent = sender.Send(msg); * * msg = Encoding.ASCII.GetBytes(txt_passwd.Text); * 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)); * 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 e3) * { * Console.WriteLine("Unexpected exception : {0}", e3.ToString()); * } * * } * catch (Exception e4) * { * Console.WriteLine(e4.ToString()); * } * // end*/ try { //epremote = new IPEndPoint(IPAddress.Parse("10.0.0.2"), Convert.ToInt32("12000")); clientSocket.Connect("10.0.0.2", 12000); STR_W = new StreamWriter(clientSocket.GetStream()); STR_R = new StreamReader(clientSocket.GetStream()); STR_W.AutoFlush = true; if (clientSocket.Connected) { STR_W.WriteLine("Login|" + txt_username.Text + "|" + txt_passwd.Text); //STR_W.WriteLine(txt_username.Text); //STR_W.WriteLine(txt_passwd.Text); string returndata; returndata = STR_R.ReadLine(); if (returndata == "Failed") { MessageBox.Show("Username or Password is incorrect"); } else { clientSocket.Close(); Variable.gusername = txt_username.Text; Variable.gusertype = returndata; MessageBox.Show("Login Successful.........!", returndata); if (returndata == "admin") { this.Hide(); AdminHome frm = new AdminHome(); frm.Show(); } if (returndata == "enduser") { this.Hide(); UserHome frm1 = new UserHome(); frm1.Show(); } if (returndata == "secmgr") { this.Hide(); SecurityManagerHome frm2 = new SecurityManagerHome(); frm2.Show(); } } /* NetworkStream serverStream = clientSocket.GetStream(); * byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Login"); * serverStream.Write(outStream, 0, outStream.Length); * //serverStream.Flush(); * NetworkStream serverStream1 = clientSocket.GetStream(); * byte[] outStream2 = System.Text.Encoding.ASCII.GetBytes(username); * serverStream1.Write(outStream, 0, outStream2.Length); * // serverStream.Flush(); * NetworkStream serverStream2 = clientSocket.GetStream(); * byte[] outStream3 = System.Text.Encoding.ASCII.GetBytes(txt_passwd.Text); * serverStream2.Write(outStream, 0, outStream3.Length); * serverStream.Flush(); * * byte[] inStream = new byte[1024]; * serverStream.Read(inStream, 0, inStream.Length); * string returndata = System.Text.Encoding.ASCII.GetString(inStream); * MessageBox.Show(returndata);*/ } } catch (Exception e4) { Console.WriteLine(e4.ToString()); } }