欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# socket

程序员文章站 2022-06-24 12:21:24
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using Sy... ......
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();
        }
    }
}