c# 使用Socket通讯简单例子  

弄了一个最简单的通讯例子,有兴趣的看看吧
使用C#进行Socket通讯.创建两个控制台项目.代码如下

服务器:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;


class Server
{
    static void Main()
    {
        try
        {
            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);//创建一个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.ASCII.GetString(recvBytes, 0, bytes);
            Console.WriteLine("服务器得到信息:{0}", recvStr);//把客户端传来的信息显示出来
            string sendStr = "hello,Clove,this is 30c server!";
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            temp.Send(bs, bs.Length, 0);//返回客户端成功信息
            temp.Close();
            s.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception:{0}", e);
        }
        Console.WriteLine("Press Enter to Exit");
        Console.ReadLine();
    }
}

客户端:

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Client
{
    static void Main()
    {
        try
        {
            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("Conneting...");
            c.Connect(ipe);//连接到服务器
            string sendStr = "hello,this is Clove speaking";
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            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.ASCII.GetString(recvBytes, 0, bytes);
            Console.WriteLine("服务器回复:{0}", recvStr);//显示服务器返回信息
            c.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception:{0}", e);
        }
        Console.WriteLine("Press Enter to Exit");
        Console.ReadLine();
    }
}

欢迎大佬支持本博客的发展 -- Donate --

本文链接:c# 使用Socket通讯简单例子

转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:三十岁,谢谢!^^


分享到:          
  1. 没有评论

  1. 没有通告