当前位置: 移动技术网 > IT编程>开发语言>c# > C# socket

C# socket

2019年11月25日  | 移动技术网IT编程  | 我要评论
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.net.sockets;
using system.io;
using system.net;

namespace consoleapp396
{
    class program
    {
        private static socket connectsocket(string server,int port)
        {
            socket s = null;
            iphostentry hostentry = null;

            //get host related information
            hostentry = dns.gethostentry(server);

            foreach(ipaddress address in hostentry.addresslist)
            {
                ipendpoint ipe = new ipendpoint(address, port);
                socket tempsocket = new socket(ipe.addressfamily, sockettype.stream, protocoltype.tcp);
                tempsocket.connect(ipe);

                if (tempsocket.connected)
                {
                    s = tempsocket;
                    break;
                }
                else
                {
                    continue;
                }
            }
            return s;
        }       
        private static string socketsendreceive(string server,int port)
        {
            string request = "get / http/1.1\r\nhost: " + server + "\r\nconnection:close\r\n\r\n";
            byte[] bytessent = encoding.ascii.getbytes(request);
            byte[] bytesreceived = new byte[256];
            string page = "";

            using(socket s = connectsocket(server, port))
            {
                if(s==null)
                {
                    return ("connection failed!");
                }

                s.send(bytessent, bytessent.length, 0);
                int bytes = 0;
                page = "default html page on " + server + ":\r\n";
                do
                {
                    bytes = s.receive(bytesreceived, bytesreceived.length, 0);
                    page = page + encoding.ascii.getstring(bytesreceived, 0, bytes);
                } while (bytes > 0);
            }
            return page;
        }
        public static void main(string[] args)
        {
            string host;
            int port = 80;
            if(args.length==0)
            {
                host = dns.gethostname();
            }
            else
            {
                host = args[0];
            }

            string result = socketsendreceive(host, port);
            console.writeline(result);
            console.readline();
        }
    }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网