C#练习:局域网内使用套接字进行信息传输
C#练习:局域网内使用套接字进行信息传输
一、在C#创建套接字socketserver和cilent。 实现步骤: 1、创建SocketServer对象。 用于监听和返回信息。①创建socket对象用于SocketSever:
socket的参数
地址族:AddressFamily.InterNetwork
套接类型:SocketType.Stream
传输协议:ProtoclType.Tcp
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
②创建IpEndPoint对象绑定当前IP(address)和监听端口Port。
Address = IPAddress.Parse(address);
Port = port;
IPEndPoint = new IPEndPoint(Address, Port);
③实现对SocketSever对象的初始化。
public class SocketServer{
...other code...
public SocketServer(string address, int port)
{
Address = IPAddress.Parse(address);
Port = port;
IPEndPoint = new IPEndPoint(Address, Port);
socket.Bind(IPEndPoint);
}
}
④实现SocketServer对象的监听功能。
创建buffer,用于接收传入的信息。
输出接收到的信息。
/// <summary>
/// 执行监听,传入的参数可限定最大的连接数量
/// </summary>
/// <param name="maxLength"></param>
public void Listen(int maxLength)
{
socket.Listen(maxLength);
Console.WriteLine($"listen in port:{IPEndPoint.Port} now");
byte[] buffer = new byte[1024];
while (true)
{
Socket temp = socket.Accept();
temp.Receive(buffer);
Console.WriteLine(buffer.Length);
Console.WriteLine(Encoding.UTF8.GetString(buffer));
byte[] buffer_response = new byte[1024];
buffer_response = Encoding.UTF8.GetBytes("received!");
temp.Send(buffer_response, 0);
}
}
⑤测试
public static void Main()
{
SocketServer server = new SocketServer("127.0.0.1", 5612);
server.Listen(10);
}
2、创建SocketCilent对象。
用于向Server端发送信息。
①创建SocketCilent对象用于向SocketServer发送信息。
public class SocketCilent
{
/// <summary>
/// 传入ip地址和监听端口来构造一个Socket服务
/// </summary>
/// <param name="address">绑定的ip地址</param>
/// <param name="port">绑定的监听端口号</param>
public SocketCilent(string address, int port)
{
Address = IPAddress.Parse(address);
Port = port;
IPEndPoint = new IPEndPoint(Address, Port);
socket.Connect(IPEndPoint);
}
}
②创建发送信息的方法
/// <summary>
/// 发送byte[]类型的信息
/// </summary>
/// <param name="msg"></param>
public void Send(string msg)
{
byte[] buffer = Encoding.UTF8.GetBytes(msg);
socket.Send(buffer,0);
socket.Receive(buffer);
Console.WriteLine(Encoding.UTF8.GetString(buffer));
socket.Close();
}
③测试
public static void Main()
{
SocketCilent cilent = new SocketCilent("127.0.0.1", 5612);
cilent.Send("broadcast message!");
}