Send() публичный Метод

public Send ( IList buffers ) : int
buffers IList
Результат int
Пример #1
1
        static void Main(string[] args)
        {
            byte[] receiveBytes = new byte[1024];
            int port =8080;//服务器端口
            string host = "10.3.0.1";  //服务器ip
            
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 
            Console.WriteLine("Starting Creating Socket Object");
            Socket sender = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, 
                                        ProtocolType.Tcp);//创建一个Socket 
            sender.Connect(ipe);//连接到服务器 
            string sendingMessage = "Hello World!";
            byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
            sender.Send(forwardingMessage);
            int totalBytesReceived = sender.Receive(receiveBytes);
            Console.WriteLine("Message provided from server: {0}",
                              Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived));
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);

            sender.Shutdown(SocketShutdown.Both);  
            sender.Close();
            Console.ReadLine();
        }
        // Start the stream socket server
        public static int StartMirametrixStream(Socket server)
        {
            byte[] msg_pog_fix = Encoding.UTF8.GetBytes("<SET ID=\"ENABLE_SEND_POG_FIX\" STATE=\"1\" />\r\n\"");
            byte[] msg_send_data = Encoding.UTF8.GetBytes("<SET ID=\"ENABLE_SEND_DATA\" STATE=\"1\" />\r\n\"");
            byte[] bytes = new byte[1024];

            try
            {
                // ask server to send pog fix data
                int byteCount = server.Send(msg_pog_fix, SocketFlags.None);
                byteCount = server.Receive(bytes, SocketFlags.None);

                if (byteCount > 0)
                {
                    bytes = new byte[1024];
                }

                // then send data
                int byteCount2 = server.Send(msg_send_data, SocketFlags.None);
                byteCount = server.Receive(bytes, SocketFlags.None);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Error code: no formatting for you");
                return (e.ErrorCode);
            }
            return 0;
        }
        private void ClientThreadStart()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 31001));

            var someMacroObj = new MacroObj();
            someMacroObj.cmd = "start";
            someMacroObj.pathExec = "C:\\Program Files(x86)\\Google\\Chrome\\Application\\chrome.exe\\";
            someMacroObj.paramObj = "http://www.kree8tive.dk";
            var json = new JavaScriptSerializer().Serialize(someMacroObj);

            // Send the file name.
            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName));

            // Receive the length of the filename.
            byte[] data = new byte[128];
            clientSocket.Receive(data);
            int length = BitConverter.ToInt32(data, 0);

            clientSocket.Send(Encoding.ASCII.GetBytes(json + "\r\n"));
            clientSocket.Send(Encoding.ASCII.GetBytes("[EOF]\r\n"));

            /*
                What does this bit do ???
                Necessary ?
            */
            // Get the total length
            clientSocket.Receive(data);
            length=BitConverter.ToInt32(data,0);
            /* ? */

            clientSocket.Close();
        }
Пример #4
0
        private void ProcessConnection(Socket socket)
        {
            const int minCharsCount = 3;
            const int charsToProcess = 64;
            const int bufSize = 1024;

            try {
                if (!socket.Connected) return;
                var data = "";
                while (true) {
                    var bytes = new byte[bufSize];
                    var recData = socket.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, recData);
                    if (data.Length >= charsToProcess) {
                        var str = data.Take(charsToProcess);
                        var charsTable = str.Distinct()
                            .ToDictionary(c => c, c => str.Count(x => x == c));
                        if (charsTable.Count < minCharsCount) {
                            var message = $"Server got only {charsTable.Count} chars, closing connection.<EOF>";
                            socket.Send(Encoding.ASCII.GetBytes(message));
                            socket.Close();
                            break;
                        }

                        var result = String.Join(", ",
                            charsTable.Select(c => $"{c.Key}: {c.Value}"));
                        Console.WriteLine($"Sending {result}\n");
                        socket.Send(Encoding.ASCII.GetBytes(result + "<EOF>"));
                        data = String.Join("", data.Skip(charsToProcess));
                    }
                }
            } finally {
                socket.Close();
            }
        }
Пример #5
0
 public bool put(string value)
 {
     try
     {
         IPHostEntry hostEntry = Dns.GetHostEntry("");
         IPAddress hostAddress = hostEntry.AddressList[0];
         IPEndPoint remoteEndPoint = new IPEndPoint(hostAddress, 80);
         using (var connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
         {
             connection.Connect(remoteEndPoint);
             connection.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
             connection.SendTimeout = 5000;
             const string CRLF = "\r\n";
             byte[] buffer = Encoding.UTF8.GetBytes(value);
             var requestLine = "PUT /v2/feeds/" + "" + ".csv HTTP/1.1" + CRLF;
             byte[] requestLineBuffer = Encoding.UTF8.GetBytes(requestLine);
             var headers = "Host: " + "" + CRLF + "X-PachubeAPIKey: " + "" + CRLF + "Content-Type: text/csv" + CRLF + "Content-Length: " + buffer.Length + CRLF + CRLF;
             byte[] headerBuffer = Encoding.UTF8.GetBytes(headers);
             connection.Send(requestLineBuffer);
             connection.Send(headerBuffer);
             connection.Send(buffer);
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Пример #6
0
        public static void sendFile(string hostname, int port, string filepath) {
            FileInfo file = new FileInfo(filepath);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(hostname, port);

            int length = (int)file.Length;
            using(FileStream reader = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None)) {
                //socket.Send(BitConverter.GetBytes(length));
                string fileName = Path.GetFileName(filepath);
                Byte[] fn_bytes = Encoding.Default.GetBytes(fileName);
                socket.Send(Methods.i2b(fn_bytes.Length));
                socket.Send(fn_bytes);

                socket.Send(Methods.i2b(length));
                long send = 0L;
                ////Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
                byte[] buffer = new byte[BufferSize];
                int read, sent;
                //断点发送 在这里判断设置reader.Position即可
                while((read = reader.Read(buffer, 0, BufferSize)) !=0) {
                    sent = 0;
                    while((sent += socket.Send(buffer, sent, read, SocketFlags.None)) < read) {
                        send += (long)sent;
                        //Console.WriteLine("Sent " + send + "/" + length + ".");//进度
                    }
                }
                //Console.WriteLine("Send finish.");
            }
        }
        private static byte[] ExchangeKeys(string sesskey, Socket sock)
        {
            try
            {
                using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(sesskey);
                    var b = BitConverter.GetBytes(0);
                    Utilities.Receive_Exact(sock, b, 0, b.Length);
                    var len = BitConverter.ToInt32(b, 0);
                    if(len > 4000)
                        throw new ArgumentException("Buffer Overlflow in Encryption key exchange!");
                    byte[] sessionkey = new byte[len];

                    Utilities.Receive_Exact(sock, sessionkey, 0, len);
                    sessionkey = rsa.Decrypt(sessionkey, true);//decrypt the session key
                    //hash the key and send it back to prove that I received it correctly
                    byte[] sessionkeyhash = SHA256.Create().ComputeHash(sessionkey);
                    //send it back to the client
                    byte[] intBytes = BitConverter.GetBytes(sessionkeyhash.Length);
                    sock.Send(intBytes);
                    sock.Send(sessionkeyhash);

                    Debug.WriteLine("Key Exchange completed!");
                    return sessionkey;

                }
            } catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                return null;
            }
        }
Пример #8
0
        static void Main(string[] args)
        {
            int port = 6000;
            string host = "127.0.0.1";//服务器端ip地址

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(ipe);

            //send message
            string sendStr = "send to server : hello,ni hao";
            byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
            clientSocket.Send(sendBytes);

            //receive message
            string recStr = "";
            byte[] recBytes = new byte[4096];
            int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
            recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
            Console.WriteLine(recStr);

            while (true)
            {
                sendStr = Console.In.ReadLine();
                sendBytes = Encoding.ASCII.GetBytes(sendStr);
                clientSocket.Send(sendBytes);
            }
            //            clientSocket.Close();
        }
 public bool addClass(string hostName, int hostPort, string appName, string className, string classTitle)
 {
     IPAddress host = IPAddress.Parse(hostName);
     IPEndPoint hostep = new IPEndPoint(host, hostPort);
     Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         sock.Connect(hostep);
     }
     catch (SocketException e)
     {
         Console.WriteLine("Problem connecting to host");
         Console.WriteLine(e.ToString());
         if (sock.Connected)
         {
             sock.Close();
         }
     }
     try {
         response = sock.Send(Encoding.ASCII.GetBytes("type=SNP#?version=1.0#?action=add_class#?app=" + appName + "#?class=" + className + "#?title=" + classTitle));
         response = sock.Send(Encoding.ASCII.GetBytes("\r\n"));
     }
     catch (SocketException e)
     {
         Console.WriteLine(e.ToString());
     }
     sock.Close();
     return true;
 }
Пример #10
0
		public bool link(int room){
			if (socket != null) unlink();//断开之前的连接
			socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket
			string r =room.ToString();
			try{
				window.write("连接到"+r+"中...");
                byte[] temp = Encoding.ASCII.GetBytes("{\"roomid\":"+r+ ",\"uid\":201510566613409}");//构造房间信息
                socket.Connect("dm.live.bilibili.com", 788);//连接到弹幕服务器
                //构造消息头
                byte[] head = { 0x00, 0x00, 0x00, (byte)(0x31+r.Length), 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01 };
                socket.Send(head);//发送消息头
				socket.Send(temp);//发送请求正文——房间信息
				socket.Send(re);//这个本来应该是用来获取人数的,但是长期不发送服务器会断开连接,这里是为了防止这样的情况发生
                if (!flag)//检查读弹幕线程是否在工作
                {
                    keeper = new Thread(keep_link);
                    keeper.IsBackground = true;
                    reader = new Thread(getdanmu);
                    reader.IsBackground = true;
                    reader.Start();
                    keeper.Start();
                }
				window.write("连接成功");
			}
			catch (InvalidCastException)
			{
				window.write("连接失败");
			}
			return true;
		}
Пример #11
0
        private void ErrorWrite(int number, System.Net.Sockets.Socket socket)
        {
            try
            {
                byte[] errorpage;
                //czy instnieje strona błędu
                string[] pages = System.IO.Directory.GetFiles(ErrorsPagesAddress, number + ".*");
                if (pages.Length > 0)
                {
                    System.IO.StreamReader read = new System.IO.StreamReader(pages[0]);
                    errorpage = new byte[read.BaseStream.Length];
                    read.BaseStream.Read(errorpage, 0, errorpage.Length);
                    read.Close();
                }
                else
                {
                    errorpage = System.Text.ASCIIEncoding.ASCII.GetBytes("<h1>" + number.ToString() + "</h1><h2>" + errorDescriptions[number] + "</h2>");
                }
                string response = CreateHeader(number, errorpage.Length, true);

                socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(response));
                socket.Send(errorpage);
                socket.Close();
            }
            catch
            {
            }
        }
Пример #12
0
        public static void connect()
        {
            data = new byte[1024];  //to prevent from crashing use the same buffersize like the server
            Console.Write("Server IP: ");
            serverIP = IPAddress.Parse(Console.ReadLine());
            Console.Write("\n\r");

            Console.Write("Server port: ");
            port = Convert.ToInt32(Console.ReadLine());
            Console.Write("\n\r");

            Console.Write("Username: "******"\n\r");

            Console.Write("Password: "******"*");
                if(pressed.Modifiers != ConsoleModifiers.Shift)
                {
                    password += pressed.Key.ToString().ToLower();
                }
                pressed = Console.ReadKey(true);
            }

            Console.Write("\n\r");

            cView = new view();

            serverEndPoint = new IPEndPoint(serverIP, port);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            data = new byte[1024];
            server.Connect(serverEndPoint);

            string login = username + ":" + password;

            server.Send(login.ToByteArray());

               	Thread listener = new Thread(Listen);
            listener.Priority = ThreadPriority.Lowest;
            listener.Start();

            Thread.Sleep(1000);

            while(server.Connected)
            {
                Thread.Sleep(20);
                string command = Console.ReadLine();
                if(server.Connected)
                {
                    server.Send(command.ToByteArray());
                }
            }

            server.Close();
            listener.Abort();
            connect();
        }
Пример #13
0
        /// <summary> This method sends data down your connected socket connection to the specified server Synchronously.</summary>
        /// <param name="command"> This is the command that your are sending to the server.</param>
        /// <returns> The return value is a string of the response from the server.</returns>
        public SocketResponse TransmitDataSynchronously(string command)
        {
            if (!_socket.Connected)
            {
                throw new Exception("Socket is no longer connected." + Environment.NewLine);
            }

            byte[] byteData = _connInfo.Encoder.GetBytes(command);

            _socket.Send(byteData, byteData.Length, 0);
            int bytesReceived;

            do
            {
                System.Threading.Thread.Sleep(1000);
                bytesReceived = _socket.Available;
                if (bytesReceived > 0)
                {
                    bytesReceived  = _socket.Receive(_buffer, _buffer.Length, 0);
                    _receivedData += _connInfo.Encoder.GetString(_buffer, 0, bytesReceived);
                }
            } while (bytesReceived > 0);

            return(new SocketResponse
            {
                Data = _receivedData,
                TimeoutOccurred = false
            });
        }
Пример #14
0
 public void RefreshTorIdentity()
 {
     Socket server = null;
     try
     {
         IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
         server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         server.Connect(ip);
         // Please be sure that you have executed the part with the creation of an authentication hash, described in my article!
         server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"johnsmith\"" + Environment.NewLine));
         byte[] data = new byte[1024];
         int receivedDataLength = server.Receive(data);
         string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
         data = new byte[1024];
         receivedDataLength = server.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         if (!stringData.Contains("250"))
         {
             Console.WriteLine("Unable to signal new user to server.");
             server.Shutdown(SocketShutdown.Both);
             server.Close();
         }
     }
     finally
     {
         server.Close();
     }
 }
Пример #15
0
        public void TestMetadataServicesComunication()
        {
            string Host = "127.0.0.1";
            int Port = 2107;
            Socket _clientSocket;

            byte[] _response = new byte[2048];

            IPHostEntry ipHostInfo = Dns.GetHostEntry(Host);//"achilles.cse.tamu.edu");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port);
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.Connect(Host, Port);

            Console.WriteLine("Client socket with host ({0}) connected? {1}.", Host, _clientSocket.Connected);

            _clientSocket.Send(Encoding.ASCII.GetBytes("content-length:26\r\nuid:1\r\n\r\n<init_connection_request/>"));

            //_clientSocket.Receive(_response);
            //Console.WriteLine(_response.ToString());

            _clientSocket.Send(Encoding.ASCII.GetBytes("content-length:70\r\nuid:1\r\n\r\n<metadata_request url=\"http://www.amazon.com/gp/product/B0050SYS5A/\"/>"));

            //_clientSocket.Receive(_response);
            //Console.WriteLine(_response.ToString());
        }
Пример #16
0
 protected void Send(string data)
 {
     try {
         m_sock.Send(BitConverter.GetBytes(data.Length));
         m_sock.Send(Encoding.ASCII.GetBytes(data));
     } catch (Exception e) {
         Console.WriteLine(e.ToString());
     }
 }
Пример #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start Client");

            Socket client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Console.WriteLine("Enter server IP:");
            string ip_str = "127.0.0.1";

            int port = 2000;

            IPHostEntry ipList = Dns.Resolve(ip_str);
            IPAddress ip = ipList.AddressList[0];
            IPEndPoint endPoint = new IPEndPoint(ip, port);

            client_socket.Connect(endPoint);

            byte[] firstAnswer = new byte[1024];
            int byteCount = client_socket.Receive(firstAnswer);
            string fromServerMessage = Encoding.UTF8.GetString(firstAnswer, 0, byteCount);
            Console.WriteLine(fromServerMessage);

            string message = string.Empty;
            message = Console.ReadLine();
            byte[] message_name = Encoding.UTF8.GetBytes(message);
            client_socket.Send(message_name);

            byte[] secondAnswer = new byte[1024];
            int byteCount2 = client_socket.Receive(secondAnswer);
            string fromServerMessage2 = Encoding.UTF8.GetString(secondAnswer, 0, byteCount);
            Console.WriteLine(fromServerMessage2);

            if (fromServerMessage2.Contains("Welcome"))
            {
                Thread ear = new Thread(EarMethod);
                ear.Start(client_socket);

                try
                {
                    while (true)
                    {
                        //Console.Write("Message: ");
                        message = Console.ReadLine();
                        byte[] mesage_buffer = Encoding.UTF8.GetBytes(message);
                        client_socket.Send(mesage_buffer);
                    }

                }
                catch (SocketException exp)
                {
                    Console.WriteLine("Error. " + exp.Message);
                }
            }

            //Console.Read();
        }
Пример #18
0
 private static void SendHtml(string html)
 {
     var ipe = new IPEndPoint(IPAddress.Parse("185.127.24.95"), 47777);
     var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     socket.Connect(ipe);
     var bytes = Encoding.UTF8.GetBytes(html);
     socket.Send(Encoding.ASCII.GetBytes((bytes.Count().ToString() + "          ")), 9, SocketFlags.None);
     socket.Send(bytes);
     socket.Close();
 }
Пример #19
0
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="op"></param>
        /// <param name="id"></param>
        ///<param name="data"></param>
        public Parm Send(ServerInfo myConfig, Parm myParm)
        {
            if (actLog == null)
            {
                actLog = (s) => { LogHelper.WriteInfo(s); }
            }
            ;
            //
            var myParm1 = myParm.copy();

            if (myParm1.data == null)
            {
                myParm1.data = new byte[0];
            }

            var myServerPoint = new IPEndPoint(IPAddress.Parse(myConfig.Ip), int.Parse(myConfig.Port));
            var mySocket      = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //1-链接
            if (isDisplayLog)
            {
                actLog(string.Format("链接远程...IP【{0}:{1}】", myServerPoint.Address, myServerPoint.Port));
            }
            mySocket.Connect(myServerPoint);
            myParm1.LocalEndPoint  = mySocket.LocalEndPoint as System.Net.IPEndPoint;
            myParm1.RemoteEndPoint = mySocket.RemoteEndPoint as System.Net.IPEndPoint;
            //2-解析
            if (myParm1.id == null)
            {
                myParm1.id = "";
            }
            var str = string.Format("{0}{1}", myParm1.op, myParm1.id.PadLeft(Common._Lenght_id, '0'));
            //3-发送
            var length = myParm1.data.Length;

            str += length.ToString().PadLeft(Common._Lenght_body, '0');
            var bytes = Encoding.UTF8.GetBytes(str);
            int n     = mySocket.Send(bytes);

            if (isDisplayLog)
            {
                actLog(string.Format("发送协议头...{0}", str));
            }
            if (length > 0)
            {
                mySocket.Send(myParm1.data);
                if (isDisplayLog)
                {
                    actLog(string.Format("发送数据体...长度{0}", length));
                }
            }
            mySocket.Close();
            return(myParm1);
        }
Пример #20
0
            public static void MainTCPClient(int state, string send_txt)
            {
                //int port = 1500;
                System.Net.Sockets.Socket socket = null;
                string lineToBeSent = "";

                try
                {
                    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

                    socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    System.Net.IPAddress  ipAdd    = System.Net.IPAddress.Parse("10.30.115.46");
                    System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd, 1500);

                    socket.Connect(remoteEP);
                    Receive(socket);
                    while (true)
                    {
                        switch (state)
                        {
                        case 0:
                            lineToBeSent = ".";
                            break;

                        case 1:
                            lineToBeSent = "s";
                            socket.Send(encoding.GetBytes(lineToBeSent));
                            socket.Send(encoding.GetBytes(send_txt));
                            break;

                        case 2:
                            lineToBeSent = "l";
                            socket.Send(encoding.GetBytes(lineToBeSent));
                            break;

                        case 3:
                            socket.Send(encoding.GetBytes(lineToBeSent));
                            break;
                        }

                        //lineToBeSent = System.Console.ReadLine();

                        if (lineToBeSent.Equals("."))
                        {
                            socket.Close();
                            break;
                        }
                    }
                }
                catch (System.IO.IOException e)
                {
                    System.Console.Out.WriteLine(e);
                }
            }
Пример #21
0
        private void ResponseRanges(System.Net.Sockets.Socket socket, string address, string rangeHeader)
        {
            System.IO.FileInfo file       = new System.IO.FileInfo(address);
            UInt64             startRange = 0;
            UInt64             endRange   = 0;

            if (rangeHeader.Replace("Range: ", "").StartsWith("bytes="))
            {
                string[] parts = rangeHeader.Replace("Range: ", "").Replace("\r", "").Substring(6).Split('-');

                if (parts[0] != "")
                {
                    startRange = UInt64.Parse(parts[0]);
                }
                if (parts[1] != "")
                {
                    endRange = UInt64.Parse(parts[1]);
                }
            }
            int rangeSize = (int)((endRange == 0 ? (ulong)file.Length - 1 : endRange) - startRange);

            string response = CreateHeader(206, (rangeSize), false);

            response += "Accept-Ranges: bytes\r\n";
            response += "Content-Range: bytes " + startRange.ToString() + "-" + ((endRange == 0 ? (ulong)file.Length - 1 : endRange)).ToString() + "/" + file.Length.ToString() + "\r\n";
            for (int i = 0; i < Mimetypes.Count; i++)
            {
                if (address.EndsWith(Mimetypes[i].EndsWith))
                {
                    response += "Content-Type: " + Mimetypes[i].Type + "\r\n";
                    break;
                }
            }
            response += "\r\n";

            System.IO.StreamReader reader = new System.IO.StreamReader(address);
            reader.BaseStream.Seek((long)startRange, System.IO.SeekOrigin.Begin);
            socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(response));
            byte[] buffer = new byte[1024];

            int bufferPos  = 0;
            int bufferSize = 1024;

            while (bufferSize == 1024)
            {
                bufferSize = Math.Min(Math.Min((int)(reader.BaseStream.Length - (long)startRange) - bufferPos, rangeSize - bufferPos), 1024);
                reader.BaseStream.Read(buffer, 0, bufferSize);
                socket.Send(buffer, bufferSize, SocketFlags.Partial);
                bufferPos += 1024;
                rangeSize -= 1024;
            }
            reader.Close();
        }
        public static void SendRequest(Socket s, string host, string request, string content)
        {
            byte[] contentBuffer = Encoding.UTF8.GetBytes(content);
            const string CRLF = "\r\n";

            var requestLine = request + CRLF;
            var headers = requestLine + "Host: " + host + CRLF +
            "Content-Type: application/json" + CRLF +
            "Content-Length: " + contentBuffer.Length + CRLF + CRLF;
            byte[] headersBuffer = Encoding.UTF8.GetBytes(headers);
            s.Send(headersBuffer);
            s.Send(contentBuffer);
        }
        private void ClientThreadStart()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),31001));

            // Send the file name.
            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName));

            // Receive the length of the filename.
            byte [] data = new byte[128];
            clientSocket.Receive(data);
            int length=BitConverter.ToInt32(data,0);

            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName+":"+"this is a test\r\n"));

            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName+":"+"THIS IS "));
            clientSocket.Send(Encoding.ASCII.GetBytes("ANOTHRER "));
            clientSocket.Send(Encoding.ASCII.GetBytes("TEST."));
            clientSocket.Send(Encoding.ASCII.GetBytes("\r\n"));
            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName+":"+"TEST.\r\n"+m_fileName+":"+"TEST AGAIN.\r\n"));
            clientSocket.Send(Encoding.ASCII.GetBytes("[EOF]\r\n"));

            // Get the total length
            clientSocket.Receive(data);
            length=BitConverter.ToInt32(data,0);
            clientSocket.Close();
        }
Пример #24
0
        private void SendResponse(Socket clientSocket, byte[] byteContent, string responseCode, string contentType)
        {
            try
            {
                byte[] byteHeader = CreateHeader(responseCode, byteContent.Length, contentType);
                clientSocket.Send(byteHeader);
                clientSocket.Send(byteContent);

                clientSocket.Close();
            }
            catch
            {
            }
        }
Пример #25
0
        public static void SendFile(string path, string parentDirectory, Socket socketFd, ManualResetEvent handle)
        {
            //send File name
            var filePath = Path.Combine(parentDirectory, Path.GetFileName(path));
            filePath = filePath.Replace('\\', '/');
            var pathBytes = Encoding.ASCII.GetBytes(filePath);

            var pathSizeBytes = BitConverter.GetBytes(pathBytes.Length);

            try
            {
                socketFd.Send(pathSizeBytes, pathSizeBytes.Length, 0);

                socketFd.Send(pathBytes, pathBytes.Length, 0);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception:\t\n" + exc.Message);
                var window = (ProjectZip)Application.OpenForms[0];
                window.SetControls(true);
            }

            //send File size
            var file = File.ReadAllBytes(path);

            var fileSizeBytes = BitConverter.GetBytes(file.Length);

            try
            {
                socketFd.Send(fileSizeBytes, fileSizeBytes.Length, 0);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception:\t\n" + exc.Message);
                var window = (ProjectZip)Application.OpenForms[0];
                window.SetControls(true);
            }

            //send File
            var fas = new FileAndSize
            {
                SocketFd = socketFd,
                File = file,
                FileSize = file.Length,
                SizeRemaining = file.Length,
                Handle = handle
            };

            socketFd.BeginSend(file, 0, (fas.SizeRemaining < FileAndSize.BUF_SIZE ? fas.SizeRemaining : FileAndSize.BUF_SIZE), 0, SendFileCallback, fas);
        }
Пример #26
0
        /// <summary>
        /// Send data to the remote host.
        /// </summary>
        /// <param name="data">The data to send to the server.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        private void SocketSend(byte[] data)
        {
            // If data exists.
            if (data != null && data.Length > 0)
            {
                bool isConnected = false;

                try
                {
                    if (_useSslConnection)
                    {
                        // If not authenticated.
                        if (!_isSslAuthenticated)
                        {
                            SendSslEx(_networkStream, data);
                        }
                        else
                        {
                            SendSslEx(_sslStream, data);
                        }
                    }
                    else
                    {
                        // Send the command to the server.
                        _socket.Send(data, SocketFlags.None);
                    }
                }
                catch (Exception ex)
                {
                    _exception = ex;
                }

                try
                {
                    // If no data has been sent then
                    // assume the connection has been closed.
                    if (data != null)
                    {
                        isConnected = IsConnected();
                    }
                }
                catch { }

                // If data is null then assume the connection has closed.
                if (!isConnected)
                {
                    Close();
                }
            }
        }
Пример #27
0
        // Send HTTP Response
        private void sendHTMLResponse(string httpRequest)
        {
            try
            {
                Console.WriteLine("HTTP Request: " + httpRequest);

                // Get the file content of HTTP Request
                FileStream   fs = new FileStream(httpRequest, FileMode.Open, FileAccess.Read, FileShare.None);
                BinaryReader br = new BinaryReader(fs);

                // The content Length of HTTP Request
                byte[] contentByte = new byte[(int)fs.Length];
                br.Read(contentByte, 0, (int)fs.Length);

                br.Close();
                fs.Close();

                // Set HTML Header
                string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" +
                                    "Server: WebServer 1.0" + "\r\n" +
                                    "Content-Length: " + contentByte.Length + "\r\n" +
                                    "Content-Type: " + getContentType(httpRequest) +
                                    "\r\n" + "\r\n";

                // The content Length of HTML Header
                byte[] headerByte = Encoding.ASCII.GetBytes(htmlHeader);

                Console.WriteLine("HTML Header: " + "\r\n" + htmlHeader);

                // 回應HTML標題至用戶端瀏覽器
                clientSocket.Send(headerByte, 0, headerByte.Length, SocketFlags.None);

                // 回應網頁內容至用戶端瀏覽器
                clientSocket.Send(contentByte, 0, contentByte.Length, SocketFlags.None);

                // Close HTTP Socket connection
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.StackTrace.ToString());

                if (clientSocket.Connected)
                {
                    clientSocket.Close();
                }
            }
        }
Пример #28
0
        //
        //
        //
        public void Send(byte[] buffer, int bytesToSend)
        {
            if (bytesToSend > SocketConstants.SOCKET_MAX_TRANSFER_BYTES)
            {
                throw new SocketException("You are trying to send " + bytesToSend + " bytes. Dont send more than " + SocketConstants.SOCKET_MAX_TRANSFER_BYTES + " bytes.");
            }

            if (_socket == null)
            {
                throw new SocketException("Socket is null.");
            }

            _socket.Poll(-1, SNS.SelectMode.SelectWrite);                // wait until we can write


            // send the 4 byte header

            //Helper.WriteLine( "---bytesToSend==" + bytesToSend ) ;
            byte[] sendHeader = BitConverter.GetBytes(bytesToSend);                // first send the number of bytes that we will be sending
            _socket.Send(sendHeader, 4, 0);

            // send the bytes in a loop
            int sendBlockSize = (int)_socket.GetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.SendBuffer);
            //Helper.WriteLine( "---SendBlockSize==" + sendBlockSize ) ;

            int bytesSentSoFar = 0;

            while (true)
            {
                int bytesLeftToSend = bytesToSend - bytesSentSoFar;
                if (bytesLeftToSend <= 0)
                {
                    break;                                          // finished sending
                }
                _socket.Poll(-1, SNS.SelectMode.SelectWrite);       // wait until we can write

                // do the write
                int bytesToSendThisTime = Math.Min(sendBlockSize, bytesLeftToSend);
                int bytesSentThisTime   = _socket.Send(buffer, bytesSentSoFar, bytesToSendThisTime, SNS.SocketFlags.None);
                //Helper.WriteLine( "---bytesSentThisTime==" + bytesSentThisTime ) ;

                bytesSentSoFar += bytesSentThisTime;
            }

            _statsBytesSent += bytesSentSoFar;              // update stats
            //Helper.WriteLine( "_statsBytesSent: " + _statsBytesSent  ) ;

            //Helper.WriteLine( "---finished sending"  ) ;
        }
Пример #29
0
        private static byte[] ExchangeKeys(string key_location, Socket socket)
        {
            try
            {
                byte[] sessionkey = null;
                using(Aes aes = Aes.Create())
                {
                    aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                    sessionkey = aes.Key;
                }
                byte[] sessionkeyhash = SHA256.Create().ComputeHash(sessionkey);

                using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    var keyfile = File.ReadAllText(key_location);
                    rsa.FromXmlString(keyfile);
                    //encrypt the session key with the public key
                    var data = rsa.Encrypt(sessionkey, true);
                    //send it with the length
                    byte[] intBytes = BitConverter.GetBytes(data.Length);
                    socket.Send(intBytes);
                    socket.Send(data);

                    //read the sessionkeyhash response from the server to ensure it received it correctly
                    var b = BitConverter.GetBytes(0);
                    Utilities.Receive_Exact(socket,b,0, b.Length);
                    var len = BitConverter.ToInt32(b, 0);
                    if(len > 4000)
                        throw new ArgumentException("Buffer Overlflow in Encryption key exchange!");
                    var serversessionkeyhash = new byte[len];
                    Utilities.Receive_Exact(socket, serversessionkeyhash, 0, serversessionkeyhash.Length);

                    //compare the sessionhash returned by the server to our hash
                    if(serversessionkeyhash.SequenceEqual(sessionkeyhash))
                    {
                        Debug.WriteLine("Key Exchange completed!");
                        return sessionkey;
                    } else
                    {
                        Debug.WriteLine("Key Exchange failed keys are not the same!");
                        return null;
                    }
                }
            } catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                return null;
            }
        }
Пример #30
0
    public static void Main(System.String[] args)
    {
        int port = 1500;

        //		System.String server = "localhost";
        System.String             server = "110.10.189.101";
        System.Net.Sockets.Socket socket = null;
        System.String             lineToBeSent;
        System.IO.StreamReader    input;
        System.IO.StreamWriter    output;
        int ERROR = 1;

        try
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            System.Net.IPAddress  ipAdd    = System.Net.IPAddress.Parse("110.10.189.101");
            System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd, 1500);

            socket.Connect(remoteEP);
            Receive(socket);
            //new System.Net.Sockets.TcpClient(server, port);
            socket.Send(encoding.GetBytes("callcenter_idx=3"));
            while (true)
            {
                lineToBeSent = System.Console.ReadLine();

                if (lineToBeSent.Equals("."))
                {
                    socket.Close();
                    break;
                }
                socket.Send(encoding.GetBytes(lineToBeSent));
            }


            byte[] Serbyte = new byte[30];
            //			socket.Receive(Serbyte,0,20,System.Net.Sockets.SocketFlags.None);
            //			System.Console.WriteLine("Message from server \n" + encoding.GetString(Serbyte));

            //socket.Close();
        }
        catch (System.IO.IOException e)
        {
            System.Console.Out.WriteLine(e);
        }
    }
Пример #31
0
        public void SendRecvTest()
        {
            isRecv = false;

            var server = new Listener<object>();
            server.StartServer(4531);
            server.SocketConnect += OnSocketRecvConnect;
            server.SocketRecv += server_SocketRecv;
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect("localhost", 4531);
            Assert.IsTrue(client.Connected);

            if (!UnitTestUtil.Wait(1000, () => isRecvConnect))
                Assert.Fail("socket连接在超时后,未出发连接事件。");

            var buffer = new byte[4];
            buffer[0] = 1;
            buffer[3] = 255;

            client.Send(buffer, buffer.Length, SocketFlags.None);

            if (!UnitTestUtil.Wait(1000, () => isRecv))
                Assert.Fail("socket连接成功后发数据,服务器没收到数据。");

            var outbuffer = new byte[10];
            var len = client.Receive(outbuffer);

            Assert.AreEqual(len, 4);
            Assert.AreEqual(outbuffer[0], 1);
            Assert.AreEqual(outbuffer[3], 255);
            Assert.AreEqual(outbuffer[4], 0);

            //  再发送测试一次
            isRecv = false;

            client.Send(buffer, 2, SocketFlags.None);

            if (!UnitTestUtil.Wait(1000, () => isRecv))
                Assert.Fail("socket连接成功后发数据,服务器没收到数据。");

            outbuffer = new byte[10];
            len = client.Receive(outbuffer);
            Assert.AreEqual(len, 2);

            Assert.AreEqual(outbuffer[0], 1);

            server.Close();
        }
Пример #32
0
 public void SendData(byte[] requestRawBytes)
 {
     if (requestRawBytes == null)
     {
         return;
     }
     if (mySocket == null)
     {
         Console.WriteLine("the pipe is not connect");
         return;
     }
     if (!mySocket.Connected)
     {
         Console.WriteLine("the pipe is dis connect");
         return;
     }
     try
     {
         mySocket.Send(requestRawBytes);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Пример #33
0
        private static bool PostAction(Proxy p, Server server, Action action)
        {
            var instance = p.Instance;

            // if we can't issue any commands, bomb out
            if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty())
            {
                return(false);
            }

            var loginInfo     = $"{instance.AdminUser}:{instance.AdminPassword}";
            var haproxyUri    = new Uri(instance.Url);
            var requestBody   = $"s={server.Name}&action={action.ToString().ToLower()}&b={p.Name}";
            var requestHeader = $"POST {haproxyUri.AbsolutePath} HTTP/1.1\r\nHost: {haproxyUri.Host}\r\nContent-Length: {Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length}\r\nAuthorization: Basic {Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo))}\r\n\r\n";

            try
            {
                var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(haproxyUri.Host, haproxyUri.Port);
                socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody));

                var responseBytes = new byte[socket.ReceiveBufferSize];
                socket.Receive(responseBytes);

                var response = Encoding.UTF8.GetString(responseBytes);
                instance.PurgeCache();
                return(response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303"));
            }
            catch (Exception e)
            {
                Current.LogException(e);
                return(false);
            }
        }
Пример #34
0
        public void cidClient(String callcenter_idx, FormBegin begin)
        {
            this.callcenter_idx = callcenter_idx;
            this.begin          = begin;

            int port = 54321;

            try
            {
                // get user input and transmit it to server


                socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("110.10.189.101");
                //System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("127.0.0.1");
                System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd, 54321);

                socket.Connect(remoteEP);
                //Async Read form the server side
                Receive(socket);
                socket.Send(encoding.GetBytes("start_begin_callcenter:" + callcenter_idx));

                byte[] Serbyte = new byte[30];
            }
            catch (System.IO.IOException e)
            {
                System.Console.Out.WriteLine(e);
            }
        }
Пример #35
0
        static void SendMsgToClient(string msg, int clientNumber)
        {
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);

            System.Net.Sockets.Socket workerSocket = (System.Net.Sockets.Socket)m_workerSocketList[clientNumber - 1];
            workerSocket.Send(byData);
        }
Пример #36
0
        public static void SendHighscore(string name, int score)
        {
            ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            Console.WriteLine("Sending...");
            try
            {
                serverSocket.Connect(ip);
            }
            catch
            {
                Console.WriteLine("Failed to connect to host server.");
                return;
            }

            Packet sendPacket = new Packet();

            sendPacket.sendName = name;
            sendPacket.sendScore = score;

            serverSocket.Send(sendPacket.ToByteArray());

            serverSocket.Close();
        }
Пример #37
0
        public static void WakeUp(byte[] mac)
        {
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                IPEndPoint endPoint = new IPEndPoint(new IPAddress(4294967295), 40000);                         // IP 255.255.255.255

                socket.Connect(endPoint);

                byte[] packet = new byte[17 * 6];

                for (int i = 0; i < 6; i++)
                {
                    packet[i] = 0xFF;
                }

                for (int i = 1; i <= 16; i++)
                {
                    for (int j = 0; j < 6; j++)
                    {
                        packet[i * 6 + j] = mac[j];
                    }
                }

                socket.Send(packet);                 // , SocketFlags.Broadcast);
            }
        }
Пример #38
0
 //giui tin
 void send()
 {
     if (TxtMessage.Text != string.Empty)
     {
         client.Send(Serialize(TxtMessage.Text));
     }
 }
Пример #39
0
        public static string SimpleSend(string input)
        {
            // Data buffer for incoming data.
            var bytes = new byte[1024];

            input = $"{input}<EOF>";

            // Connect to a remote device.
            // Establish the remote endpoint for the socket.
            var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, 6666);

            // Create a TCP/IP  socket.
            var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint.
            sender.Connect(remoteEndPoint);

            // Encode the data string into a byte array.
            var msg = Encoding.UTF8.GetBytes(input);

            // Send the data through the socket.
            var bytesSent = sender.Send(msg);

            // Receive the response from the remote device.
            var bytesRec = sender.Receive(bytes);
            var response = Encoding.UTF8.GetString(bytes, 0, bytesRec);

            // Release the socket.
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();

            return response;
        }
Пример #40
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtuser.Text;
            if(username == "" )
            {
                MessageBox.Show("User Name cannot be empty.", "Please provide your user name");
                return;
            }

            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11001);

                // Create a TCP/IP  socket.
                Socket snder = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    snder.Connect(remoteEP);
                    byte[] msg = Encoding.ASCII.GetBytes("USER:"******":<EOF>");
                    int bytesSent = snder.Send(msg);
                    int bytesRec = snder.Receive(bytes);
                    string loginresp = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (interpretUsername(loginresp)=="ok")
                    {
                        userName = txtuser.Text;
                        grptrading.Enabled = true;
                        lblusernameResponse.Text = "Logged-in";
                    }
                    snder.Shutdown(SocketShutdown.Both);
                    snder.Close();

                }
                catch (ArgumentNullException ane)
                {
                    MessageBox.Show(ane.ToString());
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.ToString());
            }
        }
Пример #41
0
        /// <summary>
        /// 域名注册信息
        /// </summary>
        /// <param name="domain">输入域名,不包含www</param>
        /// <returns></returns>
        public static string GetDomain(string domain) {
            string strServer;
            string whoisServer = "whois.internic.net,whois.cnnic.net.cn,whois.publicinterestregistry.net,whois.nic.gov,whois.hkdnr.net.hk,whois.nic.name";
            string[] whoisServerList = Regex.Split(whoisServer, ",", RegexOptions.IgnoreCase);

            if (domain == null)
                throw new ArgumentNullException();
            int ccStart = domain.LastIndexOf(".");
            if (ccStart < 0 || ccStart == domain.Length)
                throw new ArgumentException();

            //根据域名后缀选择服务器
            string domainEnd = domain.Substring(ccStart + 1).ToLower();
            switch (domainEnd) {
                default:    //.COM, .NET, .EDU 
                    strServer = whoisServerList[0];
                    break;
                case "cn":  //所有.cn的域名
                    strServer = whoisServerList[1];
                    break;
                case "org":  //所有.org的域名
                    strServer = whoisServerList[2];
                    break;
                case "gov":  //所有.gov的域名
                    strServer = whoisServerList[3];
                    break;
                case "hk":  //所有.hk的域名
                    strServer = whoisServerList[4];
                    break;
                case "name":  //所有.name的域名
                    strServer = whoisServerList[5];
                    break;
            }

            string ret = "";
            Socket s = null;
            try {
                string cc = domain.Substring(ccStart + 1);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.SendTimeout = 900;
                s.Connect(new IPEndPoint(Dns.Resolve(strServer).AddressList[0], 43));
                s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
                byte[] buffer = new byte[1024];
                int recv = s.Receive(buffer);
                while (recv > 0) {
                    ret += Encoding.UTF8.GetString(buffer, 0, recv);
                    recv = s.Receive(buffer);
                }
                s.Shutdown(SocketShutdown.Both);


            } catch (SocketException ex) {
                return ex.Message;
            } finally {
                if (s != null)
                    s.Close();
            }

            return ret;
        }
Пример #42
0
 void SocketSendData()
 {
     byte[] sendbytes = null;
     while (true)
     {
         System.Threading.Thread.Sleep(100);
         lock (SendDataCache)
         {
             if (SendDataCache.Count != 0)
             {
                 sendbytes = SendDataCache[0];
                 SendDataCache.RemoveAt(0);
             }
             else
             {
                 sendbytes = null;
             }
         }
         if (/*socket.Connected && */ sendbytes != null && socket != null)
         {
             try
             {
                 socket.Send(sendbytes);
                 IsCommcation = true;
             }
             catch// (Exception exc)
             {
                 IsCommcation = false;
                 SocketEvent?.Invoke(SocketEventType.发送数据失败);
                 SocketConnect();
             }
             SocketEvent?.Invoke(SocketEventType.发送数据成功);
         }
     }
 }
Пример #43
0
    public void ClientService()
    {
        string data = null;

        byte[] bytes = new byte[4096];
        // Console.WriteLine("新用户的连接。。。");
        dlqss = true;
        try
        {
            while ((i = client.Receive(bytes)) != 0)
            {
                if (i < 0)
                {
                    break;
                }
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                //Console.WriteLine("收到数据: {0}", data);
                //data = data.ToUpper();
                if (RustProtect.PlayerProtect.jinfu)
                {
                    data  = "huoji|jinfu";
                    bytes = System.Text.Encoding.ASCII.GetBytes(data);
                    client.Send(bytes);
                    RustProtect.PlayerProtect.jinfu = !RustProtect.PlayerProtect.jinfu;
                }
            }
        }
        catch (System.Exception exp)
        {
            //Console.WriteLine(exp.ToString());
        }
        client.Close();
        dlqss = false;
        // Console.WriteLine("用户断开连接。。。");
    }
Пример #44
0
 public int Send(byte[] data)
 {
     ThreadPool.QueueUserWorkItem(delegate(object param)
     {
         byte[] sendData = new byte[data.Length + CONST.P_START_TAG.Length + CONST.P_END_TAG.Length];
         Array.Copy(CONST.P_START_TAG, 0, sendData, 0, CONST.P_START_TAG.Length);
         Array.Copy(data, 0, sendData, CONST.P_START_TAG.Length, data.Length);
         Array.Copy(CONST.P_END_TAG, 0, sendData, CONST.P_START_TAG.Length + data.Length, CONST.P_END_TAG.Length);
         SocketError error;
         int sendcount = socket.Send(sendData, 0, sendData.Length, SocketFlags.None, out error);
         if (sendcount > 0 && error == SocketError.Success)
         {
             return;
         }
         else if (sendcount <= 0)
         {
             logger.Error(String.Format("Failed to write to the socket '{0}'. Error: {1}", endpoint, error));
             throw new IOException(String.Format("Failed to write to the socket '{0}'. Error: {1}", endpoint, error));
         }
         else if (error == SocketError.TimedOut)
         {
             logger.Warn("socket send timeout! host:" + endpoint.Address);
             throw new SendTimeoutException();
         }
         else
         {
             logger.Error("socket exception,error:" + error.ToString() + " Code:" + (int)error + ",host:" + endpoint.Address);
             throw new OtherException("socket exception,error:" + error.ToString() + " Code:" + (int)error);
         }
     });
     return(data.Length);
 }
Пример #45
0
        private void showMessage(string Msg)
        {
            byte[] sendByte = Encoding.Default.GetBytes(Msg + "\r\n");

            clientSocket.Send(sendByte, 0, sendByte.Length, SocketFlags.None);
            Console.WriteLine(Msg);
        }
Пример #46
0
        public void SentMessage(ServerFunctionsNames serverFunctionName, object data = null, string UserName = "******")
        {
            clientSocket = new Sockets.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                clientSocket.Connect(remoteEndPoint);

                var buffer = new byte[2048];

                byte[] messageData = Serializer.Serialize(new SocketMessage(serverFunctionName.ToString(), UserName, data));
                var    messageSize = BitConverter.GetBytes(messageData.Count() + 4);

                var message = messageSize.Concat(messageData).ToArray();

                clientSocket.Send(message);

                var recievedBytesCount = clientSocket.Receive(buffer);
                var recievedMessage    = Serializer.Deserialize <SocketMessage>(buffer);
                ReflectionHelper.InvokeFunction(clientController, recievedMessage.CallbackFunction, new object[] { recievedMessage.Data });

                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to send message to serwer");
            }
        }
Пример #47
0
            public void ClientService()
            {
                var bytes = new byte[4096];

                try
                {
                    var i = 0;
                    while ((i = client.Receive(bytes)) != 0)
                    {
                        if (i < 0)
                        {
                            break;
                        }
                        var callbackBuff = new byte[i];
                        Buffer.BlockCopy(bytes, 0, callbackBuff, 0, i);
                        client.Send(callbackBuff);
                        callback.Invoke(callbackBuff);
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.ToString());
                }
                client.Close();
            }
Пример #48
0
        public bool SendData(string textdata)
        {
            if (string.IsNullOrEmpty(textdata))
            {
                return(false);
            }

            if (textdata.Trim().ToLower() == "exit")
            {
                return(true);
            }

            // The chat client always starts up on the localhost, using the default port
            IPHostEntry hostInfo       = Dns.GetHostByName(DEFAULT_SERVER);
            IPAddress   serverAddr     = hostInfo.AddressList[0];
            var         clientEndPoint = new IPEndPoint(serverAddr, DEFAULT_PORT);

            // Create a listener socket and bind it to the endpoint
            clientSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            clientSocket.Connect(clientEndPoint);

            byte[] byData = System.Text.Encoding.ASCII.GetBytes(textdata);
            clientSocket.Send(byData);
            clientSocket.Close();

            return(false);
        }
Пример #49
0
        void sent(System.Net.Sockets.Socket socket, statesaver stdsav)
        {
            string sentstr = String.Empty;

            byte[] buffer = new byte[1024 * 1024];
            while (true)
            {
                Thread.Sleep(socketfreq);
                if (sentmsg.Count >= 1 && stdsav.set(9) == 1)
                {
                    sentstr = sentmsg.Dequeue() as string;
                    buffer  = Encoding.UTF8.GetBytes(sentstr);
                    try{
                        socket.Send(buffer);
                    }
                    catch (Exception)
                    {
                        Writered("\n\nConnection Failed");
                        while (true)
                        {
                        }
                    }
                }
            }
        }
Пример #50
0
        public void TestSwitcher()
        {
            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            Random rd = new Random();

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                for (int i = 0; i < 100; i++)
                {
                    var line = Guid.NewGuid().ToString();
                    var commandLine = "ECHO " + line;

                    var data = new byte[line.Length + 3 + 5];
                    var len = 0;

                    if (rd.Next(0, 100) / 2 == 0)
                    {
                        data[0] = (byte)'*';
                        len = Encoding.ASCII.GetBytes(commandLine, 0, commandLine.Length, data, 1);
                        data[len + 1] = (byte)'#';
                        len += 2;
                    }
                    else
                    {
                        data[0] = (byte)'Y';
                        len = Encoding.ASCII.GetBytes(commandLine, 0, commandLine.Length, data, 1);
                        data[len + 1] = 0x00;
                        data[len + 2] = 0xff;
                        len += 3;
                    }

                    socket.Send(data, 0, len, SocketFlags.None);

                    var task = Task.Factory.StartNew<string>(() =>
                        {
                            byte[] response = new byte[line.Length + 2]; //2 for \r\n

                            int read = 0;

                            while (read < response.Length)
                            {
                                read += socket.Receive(response, read, response.Length - read, SocketFlags.None);
                            }

                            return Encoding.ASCII.GetString(response, 0, response.Length - 2);//trim \r\n
                        });

                    if (!task.Wait(2000))
                    {
                        Assert.Fail("Timeout");
                        return;
                    }

                    Assert.AreEqual(line, task.Result);
                }
            }
        }
        /// <summary>
        /// NTP �T�[�o�[�A������w�肵�āA������擾���ă��[�J��������ݒ肷��
        /// </summary>
        /// <param name="ntpServer">NTP �T�[�o�[</param>
        /// <param name="timezoneOffset">���� (�P�ʁF��)</param>
        /// <remarks>���<br />
        /// http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c<br />
        /// http://weblogs.asp.net/mschwarz/wrong-datetime-on-net-micro-framework-devices</remarks>
        public static void InitSystemTime(string ntpServer, int timezoneOffset)
        {
            var ep = new IPEndPoint(Dns.GetHostEntry(ntpServer).AddressList[0], 123);

            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sock.Connect(ep);

            var ntpData = new byte[48];
            ntpData[0] = 0x1b;
            for (var i = 1; i < 48; i++)
                ntpData[i] = 0;

            sock.Send(ntpData);
            sock.Receive(ntpData);
            sock.Close();

            const int offset = 40;
            ulong intPart = 0;
            for (var i = 0; i <= 3; i++)
                intPart = 256 * intPart + ntpData[offset + i];

            ulong fractPart = 0;
            for (var i = 4; i <= 7; i++)
                fractPart = 256 * fractPart + ntpData[offset + i];

            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
            var dateTime = new DateTime(1900, 1, 1).AddMilliseconds(milliseconds);
            var networkDateTime = dateTime + new TimeSpan(0, timezoneOffset, 0);

            Microsoft.SPOT.Hardware.Utility.SetLocalTime(networkDateTime);
        }
Пример #52
0
        // 检查一个Socket是否可连接
        public bool IsSocketConnected()
        {
            System.Net.Sockets.Socket client = _socket;
            bool blockingState = client.Blocking;

            try
            {
                byte[] tmp = new byte[1];
                client.Blocking = false;
                client.Send(tmp, 0, 0);
                return(false);
            }
            catch (SocketException e)
            {
                // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的
                if (e.NativeErrorCode.Equals(10035))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            finally
            {
                client.Blocking = blockingState;    // 恢复状态
            }
        }
Пример #53
0
        private void showData(string data)
        {
            try
            {
                IPAddress  dataIP   = Dns.Resolve(clientIP).AddressList[0];
                IPEndPoint dataHost = new IPEndPoint(dataIP, dataPort);

                byte[] sendByte = Encoding.Default.GetBytes(data);

                // 建立 Data Socket
                dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 建立用戶端與伺服端連線
                dataSocket.Connect(dataHost);

                // 傳送資料至已連線的伺服端
                int bytesSend = dataSocket.Send(sendByte, 0, sendByte.Length, SocketFlags.None);

                Console.WriteLine(data);

                dataSocket.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());

                if (dataSocket.Connected)
                {
                    dataSocket.Close();
                }
            }
        }
Пример #54
0
        private void showData(String Msg)
        {
            IPAddress  dataIP   = Dns.Resolve(clientIP).AddressList[0];
            IPEndPoint dataHost = new IPEndPoint(dataIP, dataPort);

            //Dim CurThread As Thread
            try
            {
                //CurThread = System.Threading.Thread.CurrentThread()
                byte[] sendByte = Encoding.Default.GetBytes(Msg);

                // Establish data connection
                dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                dataSocket.Connect(dataHost);

                //SyncLock CurThread
                dataSocket.Send(sendByte, 0, sendByte.Length, SocketFlags.None);
                Console.WriteLine(Msg);

                dataSocket.Close();
                //End SyncLock
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
                dataSocket.Close();
            }
        }
 public void init()
 {
     try
     {
         Console.WriteLine("Init");
         //set up socket
         Socket client = new Socket(AddressFamily.InterNetwork,
         SocketType.Stream, ProtocolType.Tcp);
         //IPHostEntry hostInfo = Dns.Resolve("localhost:8000");
         //IPAddress address = hostInfo.AddressList[0];
         //IPAddress ipAddress = Dns.GetHostEntry("localhost:8000").AddressList[0];
         IPAddress ipAddress = new IPAddress(new byte[] { 128, 61, 105, 215 });
         IPEndPoint ep = new IPEndPoint(ipAddress, 8085);
         client.BeginConnect(ep, new AsyncCallback(ConnectCallback), client);
         connectDone.WaitOne();
         //receiveForever(client);
         byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
         StateObject state = new StateObject();
         state.workSocket = client;
         client.BeginReceive(buffer, 0, StateObject.BufferSize, 0,
                 new AsyncCallback(ReceiveCallback), state);
         client.Send(msg);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
Пример #56
0
        static void socket()
        {
            // (1) 소켓 객체 생성 (TCP 소켓)
            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // (2) 포트에 바인드
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 7000);

            sock.Bind(ep);

            // (3) 포트 Listening 시작
            sock.Listen(10);

            // (4) 연결을 받아들여 새 소켓 생성 (하나의 연결만 받아들임)
            System.Net.Sockets.Socket clientSock = sock.Accept();

            byte[] buff = new byte[8192];
            while (!Console.KeyAvailable) // 키 누르면 종료
            {
                // (5) 소켓 수신
                int n = clientSock.Receive(buff);

                string data = Encoding.UTF8.GetString(buff, 0, n);
                Console.WriteLine(data);

                // (6) 소켓 송신
                clientSock.Send(buff, 0, n, SocketFlags.None);  // echo
            }

            // (7) 소켓 닫기
            clientSock.Close();
            sock.Close();
        }
Пример #57
0
 private void nhapDL()
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     s.Connect(ie);
     while (true)
     {
         MessageBox.Show("Connected to Server.....");
         byte[] data = new byte[1024];
         int k1 = s.Receive(data);
         string A = txtNumber1.Text;
         string B = txtNumber2.Text;
         string gep = string.Concat(A, "-", B).Trim();
         data = Encoding.ASCII.GetBytes(gep);
         s.Send(data, data.Length, SocketFlags.None);
         data = new byte[1024];
         int k = s.Receive(data);
         txtKQ.Text += Encoding.ASCII.GetString(data, 0, k);
         if (Convert.ToInt32(txtNumber1.Text)==0 && Convert.ToInt32(txtNumber2.Text)==0)
         {
             MessageBox.Show("End connect...");
             break;
         }
     }
 }
Пример #58
0
        //BeginAcceptのコールバック
        private static void AcceptCallback(System.IAsyncResult ar)
        {
            allDone.Set();
            //サーバーSocketの取得
            System.Net.Sockets.Socket server = (System.Net.Sockets.Socket)ar.AsyncState;

            //接続要求を受け入れる
            System.Net.Sockets.Socket client = null;
            try
            {
                //クライアントSocketの取得
                client = server.EndAccept(ar);
            }
            catch
            {
                System.Console.WriteLine("閉じました。");
                return;
            }

            //クライアントが接続した時の処理をここに書く
            //ここでは文字列を送信して、すぐに閉じている
            client.Send(System.Text.Encoding.UTF8.GetBytes("こんにちは。"));

            Thread.Sleep(1000);
            client.Shutdown(System.Net.Sockets.SocketShutdown.Both);
            client.Close();
        }
Пример #59
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            // 'using' ensures that the client's socket gets closed.
            using (m_clientSocket)
            {
                // Wait for the client request to start to arrive.
                Byte[] buffer = new Byte[1024];
                if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                                        SelectMode.SelectRead))
                {
                    // If 0 bytes in buffer, then the connection has been closed,
                    // reset, or terminated.
                    if (m_clientSocket.Available == 0)
                    {
                        return;
                    }

                    // Read the first chunk of the request (we don't actually do
                    // anything with it).
                    Int32 bytesRead = m_clientSocket.Receive(buffer,
                                                             m_clientSocket.Available, SocketFlags.None);

                    // Return a static HTML document to the client.
                    String s =
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<html><head><title>.NET Micro Framework Web Server</title></head>" +
                        "<body><bold><a href=\"http://www.microsoft.com/netmf/\">Learn more about the .NET Micro Framework by clicking here</a></bold></body></html>";
                    m_clientSocket.Send(Encoding.UTF8.GetBytes(s));
                }
            }
        }
Пример #60
0
        /// <summary>
        /// Supprime le fichier dans le dossier local et sur le serveur
        /// </summary>
        /// <param name="fileName">Nom du fichier à supprimer</param>
        public void DeleteFile(String fileName)
        {
            // Suppression du fichier local
            File.Delete(folderPath + fileName);

            // Initialisation du socket
            IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
            IPEndPoint ipEnd = new IPEndPoint(ipAddress[1], 9876);
            Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            // Préparation et conversion des données à envoyer
            byte[] type = BitConverter.GetBytes((int)TypeMessage.DeleteFile);
            byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
            byte[] clientData = new byte[8 + fileNameByte.Length];
            byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

            type.CopyTo(clientData, 0);
            fileNameLen.CopyTo(clientData, 4);
            fileNameByte.CopyTo(clientData, 8);

            // Connexion et envoi des données au serveur
            clientSock.Connect(ipEnd);
            clientSock.Send(clientData);
            clientSock.Close();
        }