SixiBroadcast/UDPServer/Frm_Server.cs

76 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace UDPServer
{
public partial class Frm_Server : Form
{
UdpClient client;
IPEndPoint endpoint;
Dictionary<string, IPEndPoint> userinfo = new Dictionary<string, IPEndPoint>();
public Frm_Server()
{
InitializeComponent();
}
private void Frm_Server_Load(object sender, EventArgs e)
{
client = new UdpClient(new IPEndPoint(IPAddress.Any, 25433));
endpoint = new IPEndPoint(IPAddress.Any, 0);
//启动客户端监听
Thread t = new Thread(new ThreadStart(ClientThread));
t.IsBackground = true;
t.Start();
}
private void button_Click(object sender, EventArgs e)
{
foreach (var item in userinfo)
{
byte[] buf = Encoding.Default.GetBytes("用户: " + item.Key + " 消息: " + msg.Text);
client.Send(buf, buf.Length, item.Value);
}
}
private void ClientThread()
{
try
{
Console.WriteLine("服务器开始监听...");
while (true)
{
byte[] buf = client.Receive(ref endpoint);
string msg = Encoding.Default.GetString(buf);
string[] info = msg.Split(' ');
if (info.Length == 3)
{
string user = info[0];
string ip = info[1];
int port = int.Parse(info[2]);
IPEndPoint addr = new IPEndPoint(IPAddress.Parse(ip), port);
if (userinfo.ContainsKey(user))
userinfo.Remove(user);
userinfo.Add(user, addr);
Console.WriteLine("用户: " + user + " 登录服务器 IP: " + ip + " 端口: " + port);
}
}
}
catch (Exception)
{
client.Close();
}
}
}
}