C#最基本的Socket编程

来源:http://www.cnblogs.com/RobotTech/archive/2007/02/15/651077.html

客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            int port = 2000;
            string host = "127.0.0.1";

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

            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            c.Connect(ipe);
            string sendStr;
            sendStr = Console.ReadLine();
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            Console.WriteLine("发送信息");
            c.Send(bs, bs.Length, 0);
            string rcvStr = "";
            byte[] rcvBytes = new byte[1024];
            int bytes = c.Receive(rcvBytes, rcvBytes.Length, 0);
            rcvStr += Encoding.ASCII.GetString(rcvBytes, 0, bytes);
            Console.WriteLine("client get message:{0}", rcvStr);
            c.Close();

            Console.WriteLine("Press Enter to Exit");
            Console.ReadKey();


        }
    }
}

服务端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 2000;
            string host = "127.0.0.1";

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

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(ipe);
            s.Listen(0);
            Console.WriteLine("等待客户端连接");

            Socket temp = s.Accept();
            Console.WriteLine("建立连接");
            string rcvStr = "";
            byte[] rcvBytes = new byte[1024];
            int bytes = temp.Receive(rcvBytes, rcvBytes.Length, 0);
            rcvStr += Encoding.ASCII.GetString(rcvBytes, 0, bytes);
            Console.WriteLine("Server get message :{0}", rcvStr);


            string sendStr = "ok!Client send message successful!";
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            temp.Send(bs, bs.Length, 0);
            temp.Close();
            s.Close();
            Console.ReadKey();

        }
    }
}

你可能感兴趣的:(C#最基本的Socket编程)