using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Threading;
namespace Win1
{
public partial class Form1 : Form
{
private ArrayList clientArray;
private Thread tThread;
private Socket socket;
public Form1()
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipe = new IPEndPoint(ip, 5000);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipe);
socket.Listen(10);
clientArray = new ArrayList();
InitializeComponent();
tThread = new Thread(new ThreadStart(onThread));
tThread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
if (clientArray.Count == 0)
{
this.listBox1.Items.Add("没有客户端连接!");
}
else
{
string sendStr = textBox1.Text;
sendStr = "服务器消息:" + sendStr;
foreach (Socket sc in clientArray)
{
try
{
byte[] bytes = Encoding.Default.GetBytes(sendStr);
sc.Send(bytes);
}
catch (SocketException ex)
{
this.listBox1.Items.Add(ex.Message);
}
}
this.listBox1.Items.Add("<" + this.textBox1.Text + ">信息已群发!");
}
}
private void onThread()
{
try
{
while (true)
{
Socket temp = socket.Accept();
string name;
if (temp != null)
{
byte[] bytes=new byte[1024];
int i=temp.Receive(bytes);
name = Encoding.Default.GetString(bytes, 0, i);
if (name.IndexOf("<policy-file-request/>") >= 0)
{
string xml = "<cross-domain-policy> "
+ "<allow-access-from domain=/"*/" to-ports=/"5000/"/>"
+ "</cross-domain-policy>/0";
byte[] _bytes = Encoding.UTF8.GetBytes(xml);
temp.Send(_bytes);
}
else
{
clientArray.Add(temp);
Thread thread = new Thread(new ParameterizedThreadStart(_thread));
thread.Start(temp);
this.listBox1.Items.Add(name + "客户端连接进入!");
this.listBox2.Items.Add(name);
}
}
}
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
private void _thread(object value)
{
Socket acceptSocket = (Socket)value;
while (true)
{
byte[] buffer = new byte[1024];
string host;
try
{
acceptSocket.Receive(buffer);
host = Encoding.Default.GetString(buffer);
host="客户端消息:"+host;
listBox1.Items.Add(host);
foreach (Socket item in clientArray)
{
item.Send(Encoding.Default.GetBytes(host));
}
}
catch
{
}
}
}
}
}
本文介绍了一个基于TCP协议的简单聊天室服务器实现方法。该服务器能够接收多个客户端连接,并允许客户端间互相发送消息。服务器使用C#语言编写,通过监听特定端口来接受客户端连接请求。
970

被折叠的 条评论
为什么被折叠?



