完整的服务器/客户端实现可能是这样的。您不需要实现两个不同的客户端程序,但客户端和服务器应该不同。这是一个如何使用广播的示例>
程序.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] argv)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// if You run the program like "CommTest.exe 10010", than it will be host.
// if You run it like "CommTest.exe localhost 10010", than it will be client connecting to localhost.
if (argv.Length == 1)
{
Application.Run(new Form2(new Host(int.Parse(argv[0]))));
}
else
{
Application.Run(new Form1(new Client(argv[0], int.Parse(argv[1]))));
}
}
}
表格1.cs
public partial class Form1 : Form
{
public Form1(NetComm.Client client)
{
_client = client;
InitializeComponent();
}
// there is a button to broadcast picture on the client.
private void Button1_Click(object sender, EventArgs e)
{
// update the image that should be broadcasted as You like.
_client.SendData(imageToByteArray(Image.FromFile("Bitmap1.bmp")));
}
NetComm.Client _client;
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += Button1_Click;
_client.DataReceived += client_DataReceived;
}
void client_DataReceived(byte[] Data, string ID)
{
Stream stream = new MemoryStream(Data); // Data is byte array
pictureBox1.Image = Image.FromStream(stream);
}
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, ImageFormat.Gif);
return ms.ToArray();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
_client.Disconnect();
}
}
客户端.cs
class Client: NetComm.Client
{
public Client(string ip, int port):base()
{
// in this example, the ids are not considered. In a real world situation Clients should send a first message to the host,
// and host should reply with a free id. That id should be in the place of Guid.NewGuid().ToString()
Connect(ip, port, Guid.NewGuid().ToString());
}
}
表格2.cs
public partial class Form2 : Form
{
public Form2(NetComm.Host host)
{
_host = host;
InitializeComponent();
}
NetComm.Host _host;
private void Form2_Load(object sender, EventArgs e)
{
button1.Click += Button1_Click;
}
// there is a button to close the connection on the host form.
private void Button1_Click(object sender, EventArgs e)
{
_host.CloseConnection();
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
_host.CloseConnection();
}
}
主机.cs
class Host: NetComm.Host
{
public Host(int port):base(port)
{
StartConnection();
DataReceived += Host_DataReceived;
}
void Host_DataReceived(string ID, byte[] Data)
{
Brodcast(Data);
}
}