C#套接字Socket编程之最简单通信

来源:互联网 发布:大数据列存储 编辑:程序博客网 时间:2024/06/05 00:52

从网上看到的,自己手打学习过程

最简单的套接字编程、实现服务器从客户端接受一条消息并返回一条消息。

基本过程:

1.根据服务器IP和端口号建立EndPoint对象

2.建立Socket对象

3.利用Socket对象的Bind方法绑定EndPoint对象

4.利用Socket的Listen方法监听

5.与客户端建立连接并用Socket的Accept创建新的Socket对象并用新对象的Receive和Send方法接收消息和返回消息

6.最后要关闭Socket连接

代码如下:

using  System.Collections.Generic;

using System.Net;

using System.Net.Sockets;

class Program{

static void Main(string[] args)
        {
            string host = "127.0.0.1";//定义了一个服务器主机号
            int port = 1000;//端口号
            IPAddress ip = IPAddress.Parse(host);//获取服务器Ip
            IPEndPoint endPoint = new IPEndPoint(ip, port);//定义EndPoint对象
            Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//定义一个socket对象
            socket1.Bind(endPoint);//绑定endpoint对象
            socket1.Listen(0);//监听
            Console.WriteLine("建立连接:");
            Socket tempSocket = socket1.Accept();//创建一个新的socket用于与客户端通信
            string strReceive = "";
            Byte[] receiveBytes = new Byte[1024];
            int ibyte=tempSocket.Receive(receiveBytes,receiveBytes.Length,0);//接受信息
            strReceive += Encoding.ASCII.GetString(receiveBytes, 0, ibyte);
            Console.WriteLine("接受来自客户端的信息为:" + strReceive);
            string strSend = "Successful";
            Byte[] SendBytes = Encoding.ASCII.GetBytes(strSend);//发送成功响应
            tempSocket.Send(SendBytes, 0);
            tempSocket.Close();//关闭套接字
            socket1.Close();
            Console.ReadLine();
        }

}

0 0
原创粉丝点击