public void clearScore(int level) { if (level > 5 || level < 0) throw new ArgumentOutOfRangeException("level must be between 0 and 5"); IPEndPoint ip = new IPEndPoint(IPAddress.Parse("128.143.69.241"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { Console.WriteLine("Trying connection to server."); server.Connect(ip); } catch (SocketException e) { Console.WriteLine(e.StackTrace); Console.WriteLine("Unable to connect to server."); return; } double rando = new System.Random().NextDouble(); string command = "HIGHSCORE-CLEAR-" + level + "\r\n"; Console.WriteLine("Sending command \"" + command + "\"."); server.Send(Encoding.ASCII.GetBytes(command)); byte[] data = new byte[1024]; Console.WriteLine("Sent command \"" + command + "\"."); int receivedDataLength = server.Receive(data); Console.WriteLine("Received command \"" + command + "\"."); string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); Console.WriteLine("DATA FROM SERVER: " + stringData); server.Close(); }
private void Loop() { _serverSocket.Start(); _clientSocket = _serverSocket.AcceptTcpClient(); System.Net.Socket listener = new System.Net.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); while (true) { try { NetworkStream networkStream = _clientSocket.GetStream(); byte[] bytesFrom = new byte[4096]; int byteRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length); string dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, byteRead); Console.WriteLine(" >> Data from client - " + dataFromClient); /*string serverResponse = "Last Message from client" + dataFromClient; * Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse); * networkStream.Write(sendBytes, 0, sendBytes.Length); * Console.WriteLine(" >> " + serverResponse);*/ networkStream.Flush(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } }
public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key) { this.sock = sock; this.epl = epl; this.secure = secure; this.key = key; if (secure == false) { stream = new NetworkStream (sock, false); } else { SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, true, false); ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection; ssl_stream.ClientCertValidationDelegate += OnClientCertificateValidation; stream = ssl_stream; } timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite); Init (); }
public EndPointListener (IPAddress addr, int port, bool secure) { if (secure) { this.secure = secure; LoadCertificateAndKey (addr, port); } endpoint = new IPEndPoint (addr, port); sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sock.Bind (endpoint); sock.Listen (500); SocketAsyncEventArgs args = new SocketAsyncEventArgs (); args.UserToken = this; args.Completed += OnAccept; sock.AcceptAsync (args); prefixes = new Hashtable (); unregistered = new Dictionary<HttpConnection, HttpConnection> (); }
bool CreateTunnel (HttpWebRequest request, Uri connectUri, Stream stream, out byte[] buffer) { StringBuilder sb = new StringBuilder (); sb.Append ("CONNECT "); sb.Append (request.Address.Host); sb.Append (':'); sb.Append (request.Address.Port); sb.Append (" HTTP/"); if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11) sb.Append ("1.1"); else sb.Append ("1.0"); sb.Append ("\r\nHost: "); sb.Append (request.Address.Authority); bool ntlm = false; var challenge = Data.Challenge; Data.Challenge = null; var auth_header = request.Headers ["Proxy-Authorization"]; bool have_auth = auth_header != null; if (have_auth) { sb.Append ("\r\nProxy-Authorization: "); sb.Append (auth_header); ntlm = auth_header.ToUpper ().Contains ("NTLM"); } else if (challenge != null && Data.StatusCode == 407) { ICredentials creds = request.Proxy.Credentials; have_auth = true; if (connect_request == null) { // create a CONNECT request to use with Authenticate connect_request = (HttpWebRequest)WebRequest.Create ( connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/"); connect_request.Method = "CONNECT"; connect_request.Credentials = creds; } for (int i = 0; i < challenge.Length; i++) { var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds); if (auth == null) continue; ntlm = (auth.Module.AuthenticationType == "NTLM"); sb.Append ("\r\nProxy-Authorization: "); sb.Append (auth.Message); break; } } if (ntlm) { sb.Append ("\r\nProxy-Connection: keep-alive"); connect_ntlm_auth_state++; } sb.Append ("\r\n\r\n"); Data.StatusCode = 0; byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ()); stream.Write (connectBytes, 0, connectBytes.Length); int status; WebHeaderCollection result = ReadHeaders (stream, out buffer, out status); if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) && result != null && status == 407) { // Needs proxy auth var connectionHeader = result ["Connection"]; if (socket != null && !string.IsNullOrEmpty (connectionHeader) && connectionHeader.ToLower() == "close") { // The server is requesting that this connection be closed socket.Close(); socket = null; } Data.StatusCode = status; Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false); return false; } else if (status != 200) { string msg = String.Format ("The remote server returned a {0} status code.", status); HandleError (WebExceptionStatus.SecureChannelFailure, null, msg); return false; } return (result != null); }
void Connect (HttpWebRequest request) { lock (socketLock) { if (socket != null && socket.Connected && status == WebExceptionStatus.Success) { // Take the chunked stream to the expected state (State.None) if (CanReuse () && CompleteChunkedRead ()) { reused = true; return; } } reused = false; if (socket != null) { socket.Close(); socket = null; } chunkStream = null; IPHostEntry hostEntry = sPoint.HostEntry; if (hostEntry == null) { #if MONOTOUCH xamarin_start_wwan (sPoint.Address.ToString ()); hostEntry = sPoint.HostEntry; if (hostEntry == null) { #endif status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure : WebExceptionStatus.NameResolutionFailure; return; #if MONOTOUCH } #endif } //WebConnectionData data = Data; foreach (IPAddress address in hostEntry.AddressList) { try { socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } catch (Exception se) { // The Socket ctor can throw if we run out of FD's if (!request.Aborted) status = WebExceptionStatus.ConnectFailure; connect_exception = se; return; } IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port); socket.NoDelay = !sPoint.UseNagleAlgorithm; try { sPoint.KeepAliveSetup (socket); } catch { // Ignore. Not supported in all platforms. } if (!sPoint.CallEndPointDelegate (socket, remote)) { socket.Close (); socket = null; status = WebExceptionStatus.ConnectFailure; } else { try { if (request.Aborted) return; socket.Connect (remote); status = WebExceptionStatus.Success; break; } catch (ThreadAbortException) { // program exiting... Socket s = socket; socket = null; if (s != null) s.Close (); return; } catch (ObjectDisposedException) { // socket closed from another thread return; } catch (Exception exc) { Socket s = socket; socket = null; if (s != null) s.Close (); if (!request.Aborted) status = WebExceptionStatus.ConnectFailure; connect_exception = exc; } } } } }
internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg) { err_msg = null; Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); s = nstream; if (s == null) return false; } try { s.Write (buffer, offset, size); // here SSL handshake should have been done if (ssl && !certsAvailable) GetCertificates (s); } catch (Exception e) { err_msg = e.Message; WebExceptionStatus wes = WebExceptionStatus.SendFailure; string msg = "Write: " + err_msg; if (e is WebException) { HandleError (wes, e, msg); return false; } // if SSL is in use then check for TrustFailure if (ssl) { #if SECURITY_DEP && (MONOTOUCH || MONODROID) HttpsClientStream https = (s as HttpsClientStream); if (https.TrustFailure) { #else if ((bool) piTrustFailure.GetValue (s , null)) { #endif wes = WebExceptionStatus.TrustFailure; msg = "Trust failure"; } } HandleError (wes, e, msg); return false; } return true; } internal void Close (bool sendNext) { lock (this) { if (Data != null && Data.request != null && Data.request.ReuseConnection) { Data.request.ReuseConnection = false; return; } if (nstream != null) { try { nstream.Close (); } catch {} nstream = null; } if (socket != null) { try { socket.Close (); } catch {} socket = null; } if (ntlm_authenticated) ResetNtlm (); if (Data != null) { lock (Data) { Data.ReadState = ReadState.Aborted; } } state.SetIdle (); Data = new WebConnectionData (); if (sendNext) SendNext (); connect_request = null; connect_ntlm_auth_state = NtlmAuthState.None; } } void Abort (object sender, EventArgs args) { lock (this) { lock (queue) { HttpWebRequest req = (HttpWebRequest) sender; if (Data.request == req || Data.request == null) { if (!req.FinishedReading) { status = WebExceptionStatus.RequestCanceled; Close (false); if (queue.Count > 0) { Data.request = (HttpWebRequest) queue.Dequeue (); SendRequest (Data.request); } } return; } req.FinishedReading = true; req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted"); if (queue.Count > 0 && queue.Peek () == sender) { queue.Dequeue (); } else if (queue.Count > 0) { object [] old = queue.ToArray (); queue.Clear (); for (int i = old.Length - 1; i >= 0; i--) { if (old [i] != sender) queue.Enqueue (old [i]); } } } } }
internal void Close (bool force_close) { if (sock != null) { Stream st = GetResponseStream (); if (st != null) st.Close (); o_stream = null; } if (sock != null) { force_close |= !context.Request.KeepAlive; if (!force_close) force_close = (context.Response.Headers ["connection"] == "close"); /* if (!force_close) { // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 || // status_code == 413 || status_code == 414 || status_code == 500 || // status_code == 503); force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10); } */ if (!force_close && context.Request.FlushInput ()) { if (chunked && context.Response.ForceCloseChunked == false) { // Don't close. Keep working. reuses++; Unbind (); Init (); BeginReadRequest (); return; } reuses++; Unbind (); Init (); BeginReadRequest (); return; } Socket s = sock; sock = null; try { if (s != null) s.Shutdown (SocketShutdown.Both); } catch { } finally { if (s != null) s.Close (); } Unbind (); RemoveConnection (); return; } }
void CloseSocket () { if (sock == null) return; try { sock.Close (); } catch { } finally { sock = null; } RemoveConnection (); }
internal Socket Hijack (out ArraySegment<byte> buffered) { // TODO: disable normal request/response. buffered = new ArraySegment<byte> (ms.GetBuffer(), position, (int)ms.Length - position); RemoveConnection (); var s = sock; sock = null; o_stream = null; return s; }
protected void connect() { IPEndPoint ip = new IPEndPoint(IPAddress.Parse("128.143.69.241"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ip); } catch (SocketException e) { Console.WriteLine(e.StackTrace); Console.WriteLine("Unable to connect to server."); return; } server.Send(Encoding.ASCII.GetBytes("GetLogCount\r\n")); byte[] data = new byte[1024]; int receivedDataLength = server.Receive(data); string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); Console.WriteLine("DATA FROM SERVER: " + stringData); //server.Close(); }
public void getScores(int level, out int numberOfEntries, out String[] names, out int[] scores, out long[] datesInMillis) { if (level > 5 || level < 0) throw new ArgumentOutOfRangeException("level must be between 0 and 5"); IPEndPoint ip = new IPEndPoint(IPAddress.Parse("128.143.69.241"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { Console.WriteLine("Trying connection to server."); server.Connect(ip); } catch (SocketException e) { Console.WriteLine(e.StackTrace); Console.WriteLine("Unable to connect to server."); numberOfEntries = 0; names = null; scores = null; datesInMillis = null; return; } double rando = new System.Random().NextDouble(); string command = "HIGHSCORE-GET-" + level + "\r\n"; Console.WriteLine("Sending command \"" + command + "\"."); server.Send(Encoding.ASCII.GetBytes(command)); byte[] data = new byte[1024]; Console.WriteLine("Sent command \"" + command + "\"."); int receivedDataLength = server.Receive(data); Console.WriteLine("Received command \"" + command + "\"."); string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); Console.WriteLine("DATA FROM SERVER: " + stringData); //process returned data String[] splits = stringData.Split('|'); numberOfEntries = 0; foreach (String s in splits) { if (!(s == null)) if (!s.Equals("") && !s.Equals("\n")) { numberOfEntries++; } } String[] entries = new String[numberOfEntries]; int index = 0; foreach (String s in splits) { if (!(s == null)) if (!s.Equals("") && !s.Equals("\n")) { entries[index] = s; index++; //Console.WriteLine("<<" + s + ">>"); } } names = new String[numberOfEntries]; scores = new int[numberOfEntries]; datesInMillis = new long[numberOfEntries]; //Console.WriteLine("entries = " + numberOfEntries); for (int i = 0; i < numberOfEntries; i++) { //Console.WriteLine(entries[i]); String[] split = entries[i].Split('-'); names[i] = split[0]; scores[i] = Convert.ToInt32(split[1]); datesInMillis[i] = Convert.ToInt64(split[2]); } server.Close(); }