聊天室服务器:
创建项目
桌面不需要使用控件
Program.cs
internal class Program
{
static TcpListener server;
[STAThread]
static void Main()
{
Program p = new Program();
p.start();
}
void start()
{
server = new TcpListener(IPAddress.Parse(GetIP()), 3333);
server.Start(100);
// 等待客户进行连入
Thread th = new Thread(WaitClinetInto);
th.Start();
}
List<MyClient> List = new List<MyClient>();
void WaitClinetInto()
{
// 等待多个客户端进行连入
while (true)
{
// 如果现在有客户端要连入了
if (server.Pending())
{
TcpClient client = server.AcceptTcpClient();// 接受客户端连接
Console.WriteLine("有客户端连入:"+client.Client.RemoteEndPoint.ToString());
// 自定义客户端 把接受消息和发消息等功能进行封装
MyClient MC = new MyClient(client,this); // this 就是Program对象
List.Add(MC);
Thread.Sleep(100);
}
}
}
// 群发消息
public void ChatGroup(string msg, MyClient my)
{
foreach (MyClient item in List)
{
if (my != item)
{
item.sendMessage(msg);
}
}
}
// 选择IP
string GetIP()
{
Console.WriteLine("1.我的线上IP:192.168.107.72");
Console.WriteLine("2.测试我的服务器:127.0.0.1");
Console.WriteLine("3.其他IP地址");
string num = Console.ReadLine();
string ip = "";
if (num == "1")
{
ip = "192.168.107.72";
}
else if (num =="2")
{
ip = "127.0.0.1";
}
else
{
Console.WriteLine("请输入你想连的服务器ip");
ip = Console.ReadLine();
}
Console.WriteLine("我选择的IP是:"+ip);
return ip;
}
}
选着ip形式三个CW输入1,2,3选择
MyClient.cs
internal class MyClient
{
public TcpClient Client; // Program文件获取客户端对象
public Program Program; // program对象
public NetworkStream Stream; // 接受或者发送消息
public MyClient(TcpClient t1,Program p)
{
this.Client = t1;
this.Program = p;
this.Stream = t1.GetStream();
// 开始接受数据 在异步接受数据
// 开启分线程
Thread th = new Thread(MytheadHandle);
th.Start();
}
// 处理收发消息的
public void MytheadHandle()
{
while (true)
{
try
{
byte[] bs = new byte[1024];
// 接受数据
int length = this.Stream.Read(bs, 0, bs.Length);
string msg = Encoding.UTF8.GetString(bs, 0, length);
Console.WriteLine(msg);
if (!String.IsNullOrEmpty(msg))
{
// 调用群聊的方法
this.Program.ChatGroup(msg,this);
}
}
catch(Exception ex)
{
Console.WriteLine("111"+ex.Message);
break;
}
}
}
// 封装一个发送消息的方法
public void sendMessage(string msg)
{
try
{
byte[] bs = Encoding.UTF8.GetBytes(msg);
this.Stream.Write(bs, 0, bs.Length);
}
catch (Exception e)
{
this.Client.Close();
Console.WriteLine("222" + e.Message);
}
}
}
右键项目属性选择输出类型“控制台应用程序”
运行效果服务器启动成功