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();

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值