视频已经发布,这里是所有的代码仅供参考.
TCP服务器:
MainWindow里面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading; namespace TCPServerExample
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
TcpListener myListener;
List<User> userList = new List<User>();
bool isExit;
IPAddress ip;
public MainWindow()
{
InitializeComponent();
button1.IsEnabled = true;
button2.IsEnabled = false;
}
//开始按钮
private void button1_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
button2.IsEnabled = true;
isExit = true;
//获取本机IP地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (var item in ips)
{
if (item.AddressFamily==AddressFamily.InterNetwork)
{
ip = item;
break;
}
} myListener = new TcpListener(ip, );
IPEndPoint iep = new IPEndPoint(ip, );
myListener.Start();
//textBlock1.Text += string.Format("服务器在{0}的{1}打开监听",ips[5],port);
textBlock1.Text += string.Format("服务器在{0}打开监听\n", iep);
Thread t1 = new Thread(ListenClientConnect);
t1.Start();
} //第一步,开启监听
private void ListenClientConnect()
{
//获取相应客户端套接字
while (isExit)
{
try
{
TcpClient newClient = myListener.AcceptTcpClient();
User user = new User(newClient);
userList.Add(user);
Action act = delegate()
{
textBlock1.Text += string.Format("用户{0}连接成功,当前在线用户数为{1}\n",
newClient.Client.RemoteEndPoint, userList.Count);
};
textBlock1.Dispatcher.Invoke(act);
Thread t2 = new Thread(ReceiveMessage);
t2.Start(user);
}
catch
{
break;
} }
}
//第二步,接收消息
private void ReceiveMessage(Object user1)
{
User newuser = (User)user1;
while (isExit)
{
try
{
string message = newuser.br.ReadString();
AddMessage(string.Format("客户端:{0}发送信息:{1}\n",
newuser.client.Client.RemoteEndPoint, message));
string[] array = message.Split(',');
switch (array[])
{
case "Login":
{
newuser.username = array[];
//服务器告诉所有在线客户端,有新的用户登录
for (int i = ; i < userList.Count; i++)
{
if (userList[i].username != newuser.username)
{
userList[i].bw.Write("Login," + array[]);
}
newuser.bw.Write("Login," + userList[i].username);
}
break;
}
case "Logout":
{
for (int i = ; i < userList.Count; i++)
{
if (userList[i].username != newuser.username)
{
userList[i].bw.Write("Logout," + array[]);
}
}
userList.Remove(newuser);
AddMessage("客户端" + newuser.username + "退出," + "当前用户数为:" + userList.Count);
return;
}
case "Talk":
{
string target = array[];
for (int i = ; i < userList.Count; i++)
{
if (userList[i].username == target)
{
userList[i].bw.Write("Talk," + newuser.username + "," + array[]);
}
}
break;
}
default:
{
MessageBox.Show("什么意思?");
break;
}
}
}
catch
{
break;
}
}
}
//第三步,添加消息到textBlock
private void AddMessage(string message)
{
Action act = delegate()
{
textBlock1.Text += message;
};
textBlock1.Dispatcher.Invoke(act);
} //结束按钮
private void button2_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = true;
button2.IsEnabled = false;
for (int i = ; i < userList.Count; i++)
{
try
{
userList[i].bw.Write("服务器已停止监听!");
}
catch
{
break;
}
userList[i].Close();
}
isExit = false;
Thread.Sleep();
myListener.Stop(); for (int i = ; i < userList.Count; i++)
{
userList[i].Close();
}
textBlock1.Text += "监听结束!";
}
}
}
User类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO; namespace TCPServerExample
{
class User
{
public string username{get;set;}
public TcpClient client{get;set;}
public BinaryWriter bw { get; set; }
public BinaryReader br { get; set; }
public User(TcpClient newclient)
{
this.client = newclient;
NetworkStream networkstream = newclient.GetStream();
bw = new BinaryWriter(networkstream);
br = new BinaryReader(networkstream); } public void Close()
{
client.Close();
bw.Close();
br.Close(); }
}
}
TCP客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading; namespace TCPClientExample
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
TcpClient newClient;
BinaryWriter bw;
BinaryReader br;
string username;
//enum item { listBox1, textBox1 };
//enum opreation { add,remove};
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
username = textBox2.Text;
//创建套接字(TcpClient对象)
newClient = new TcpClient();
//获取服务器IP地址
IPAddress ip = IPAddress.Parse("10.0.2.15");
try
{
newClient.Connect(ip, );
listBox1.Items.Add("连接成功!");
}
catch
{
listBox1.Items.Add("连接失败!");
button1.IsEnabled = true;
return;
}
NetworkStream networkStream = newClient.GetStream();
bw = new BinaryWriter(networkStream);
br = new BinaryReader(networkStream);
bw.Write("Login," + username);
Thread t1 = new Thread(ReceiveMessage);
t1.Start();
}
//第一步,接收消息
private void ReceiveMessage()
{
string message = "";
while (true)
{
try
{
message = br.ReadString();
}
catch
{
break;
}
string[] array = message.Split(',');
switch (array[])
{
case "Login":
AddUser(array[]);
break;
case "Logout":
RemoveUser(array[]);
break;
case "Talk":
AddMessage(array[] + ":" + array[]);
break;
default:
AddMessage(message);
break;
}
}
}
//第二步,添加消息到textBlock
private void AddMessage(string message)
{
Action act = delegate()
{
listBox1.Items.Add(message);
};
listBox2.Dispatcher.Invoke(act);
}
//第三步,添加用户到列表
private void AddUser(string name)
{
Action act = delegate()
{
listBox2.Items.Add(name);
};
listBox2.Dispatcher.Invoke(act);
}
//第四步,移除用户
private void RemoveUser(string name)
{
Action act = delegate()
{
listBox2.Items.Remove(name);
};
listBox2.Dispatcher.Invoke(act);
} private void button2_Click(object sender, RoutedEventArgs e)
{
NetworkStream networkStream = newClient.GetStream();
bw = new BinaryWriter(networkStream);
string message = textBox1.Text;
bw.Write("Talk,"+listBox2.SelectedItem+","+message);
listBox1.Items.Add(username + ":" + textBox1.Text);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
bw.Write("Logout," + username);
}
catch
{
MessageBox.Show("与服务器连接失败!");
}
bw.Close();
}
}
}
我这里的ip都是我自己电脑的ip,你们参考别忘了改ip
我是蜀云泉,我爱许嵩.吼吼~