C# Socket 编程简单实例

C# Console 编程

 

服务器端:csharpconsolesokecttestserver.cs

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Net.Sockets;

 

namespace csharpconsolesokecttestserver

{

    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);//把ip和端口转化为IPEndPoint实例

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket

            s.Bind(ipe);//绑定2000端口

            s.Listen(0);//开始监听

            Console.WriteLine("等待连接...");

            Socket temp=s.Accept();//为新建连接创建新的Socket。

            Console.WriteLine("连接成功...");

            string recvstr = "";

            byte[] recvbytes = new byte[1024];

            int bytes;

            bytes = temp.Receive(recvbytes, recvbytes.Length, 0);//从客户端接受信息

            recvstr += Encoding.UTF8.GetString(recvbytes, 0, bytes);//将byte转换成str,编码用UTF-8

            Console.WriteLine("服务器端获取信息为:/n{0}",recvstr);

            string sendstr = "服务器已接受来自客户端的信息.";

            byte[] bs = Encoding.UTF8.GetBytes(sendstr);

            temp.Send(bs,bs.Length,0);

            temp.Close();

            s.Close();

            Console.ReadLine();

        }

    }

}

 

客户端:csharpconsolesockettestclinet.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace csharpconsolesockettestclinet
{
    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);//把ip和端口转化为IPEndPoint实例
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
            Console.WriteLine("连接服务器...");
            c.Connect(ipe);//连接到服务器
            string sendStr = "这是从客户端发送的一条信息。";
            byte[] bs = Encoding.UTF8.GetBytes(sendStr);//将str转换成byte,编码用UTF-8
            Console.WriteLine("信息发送");
            c.Send(bs, bs.Length, 0);//发送信息
            string recvStr = "";
            byte[] recvBytes = new byte[1024];
            int bytes;
            bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受信息
            recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
            Console.WriteLine("客户端获取信息为:/n{0}", recvStr);//显示服务器信息
            c.Close();
            Console.ReadLine();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值