1.服务器端的编写
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
internal class Test
{
public static void Main()
{
Socket tcpServer=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//地址家族类型:因特网,套接字类型:数据流,数据报类型:tcp
IPAddress ipaddress=new IPAddress(new byte[]{122,206,79,172}); //定义一个ip地址
EndPoint point = new IPEndPoint(ipaddress, 7788); //使用ip和端口表示地址
tcpServer.Bind(point); //绑定端口
tcpServer.Listen(100); //监听数量设定为100
Socket clientSocket = tcpServer.Accept(); //开始接受消息并得到客户的socket地址
string message = "欢迎连接";
byte[] data = Encoding.UTF8.GetBytes(message); //将字符转换为字节数组
clientSocket.Send(data); //发送数据
}
}
2.客户端的编写
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace client
{
class Program
{
static void Main(string[] args)
{
Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddress address = IPAddress.Parse("127.0.0.1");
EndPoint point=new IPEndPoint(address,9789);
socket.Connect(point);
byte[] data = new byte[1024];
int length = socket.Receive(data); //接受数据返回接受的数据
string message = Encoding.UTF8.GetString(data, 0, length); //转换成字符串
Console.WriteLine(message); //输出数据
Console.ReadKey();
}
}
}
c#Socket通信(一)实例复习
最新推荐文章于 2023-05-30 20:12:19 发布