聊天工具
来源:互联网 发布:傻瓜记账软件 编辑:程序博客网 时间:2024/05/08 12:01
SyncChatClient
-----MainForm.cs-------
using System;
using System.Windows.Forms;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
//该源码下载自C#编程网|www.cpbcw.com
namespace SyncChatClient
{
public partial class MainForm : Form
{
private bool isExit = false;
private TcpClient client;
private BinaryReader br;
private BinaryWriter bw;
public MainForm()
{
InitializeComponent();
Random r = new Random((int)DateTime.Now.Ticks);
textBoxUserName.Text = "user" + r.Next(100, 999);
listBoxOnlineStatus.HorizontalScrollbar = true;
}
/// <summary>
/// 【连接服务器】按钮的Click事件
/// </summary>
private void buttonConnect_Click(object sender, EventArgs e)
{
buttonConnect.Enabled = false;
try
{
//此处为方便演示,实际使用时要将Dns.GetHostName()改为服务器域名
client = new TcpClient(Dns.GetHostName(), 51888);
AddTalkMessage("连接成功");
}
catch
{
AddTalkMessage("连接失败");
buttonConnect.Enabled = true;
return;
}
//获取网络流
NetworkStream networkStream = client.GetStream();
//将网络流作为二进制读写对象
br = new BinaryReader(networkStream);
bw = new BinaryWriter(networkStream);
SendMessage("Login," + textBoxUserName.Text);
Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
threadReceive.IsBackground = true;
threadReceive.Start();
}
/// <summary>处理接收的服务器端数据</summary>
private void ReceiveData()
{
string receiveString = null;
while (isExit == false)
{
try
{
//从网络流中读出字符串
//此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串
receiveString = br.ReadString();
}
catch
{
if (isExit == false)
{
MessageBox.Show("与服务器失去联系。");
}
break;
}
string[] splitString= receiveString.Split(',');
string command = splitString[0].ToLower();
switch (command)
{
case "login": //格式:login,用户名
AddOnline(splitString[1]);
break;
case "logout": //格式:logout,用户名
RemoveUserName(splitString[1]);
break;
case "talk": //格式:talk,用户名,对话信息
//AddTalkMessage(splitString[1] + ":\r\n");
//AddTalkMessage(receiveString.Substring(
// splitString[0].Length + splitString[1].Length+2));
AddTalkMessage(string.Format("[{0}]说:{1}",
splitString[1],receiveString.Substring(
splitString[0].Length + splitString[1].Length + 2)));
break;
default:
AddTalkMessage("什么意思啊:" + receiveString);
break;
}
}
Application.Exit();
}
/// <summary>向服务器端发送信息</summary>
private void SendMessage(string message)
{
try
{
//将字符串写入网络流,此方法会自动附加字符串长度前缀
bw.Write(message);
bw.Flush();
}
catch
{
AddTalkMessage("发送失败!");
}
}
/// <summary>【发送】按钮的Click事件</summary>
private void buttonSend_Click(object sender, EventArgs e)
{
if (listBoxOnlineStatus.SelectedIndex != -1)
{
//SendMessage("Talk," + listBoxOnlineStatus.SelectedItem + "," + textBoxSend.Text+"\r\n");
SendMessage("Talk," + listBoxOnlineStatus.SelectedItem + "," + textBoxSend.Text);
textBoxSend.Clear();
}
else
{
MessageBox.Show("请先在[当前在线]中选择一个对话者");
}
}
/// <summary>关闭窗口时触发的事件</summary>
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
//未与服务器连接前client为null
if (client != null)
{
SendMessage("Logout," + textBoxUserName.Text);
isExit = true;
br.Close();
bw.Close();
client.Close();
}
}
/// <summary>在发送信息文本框中按下【Enter】键触发的事件</summary>
private void textBoxSend_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
//触发buttonSend的Click事件
buttonSend.PerformClick();
}
}
private delegate void MessageDelegate(string message);
/// <summary> 在richTextBoxTalkInfo中追加聊天信息</summary>
private void AddTalkMessage(string message)
{
if (richTextBoxTalkInfo.InvokeRequired)
{
MessageDelegate d = new MessageDelegate(AddTalkMessage);
richTextBoxTalkInfo.Invoke(d, new object[] { message });
}
else
{
richTextBoxTalkInfo.AppendText(message + Environment.NewLine);
richTextBoxTalkInfo.ScrollToCaret();
}
}
private delegate void AddOnlineDelegate(string message);
/// <summary> 在listBoxOnlineStatus中添加在线的其它客户端信息</summary>
private void AddOnline(string userName)
{
if (listBoxOnlineStatus.InvokeRequired)
{
AddOnlineDelegate d = new AddOnlineDelegate(AddOnline);
listBoxOnlineStatus.Invoke(d, new object[] { userName });
}
else
{
listBoxOnlineStatus.Items.Add(userName);
listBoxOnlineStatus.SelectedIndex = listBoxOnlineStatus.Items.Count - 1;
listBoxOnlineStatus.ClearSelected();
}
}
private delegate void RemoveUserNameDelegate(string userName);
/// <summary> 在listBoxOnlineStatus中移除不在线的其它客户端信息</summary>
private void RemoveUserName(string userName)
{
if (listBoxOnlineStatus.InvokeRequired)
{
RemoveUserNameDelegate d = RemoveUserName;
listBoxOnlineStatus.Invoke(d, userName);
}
else
{
listBoxOnlineStatus.Items.Remove(userName);
listBoxOnlineStatus.SelectedIndex = listBoxOnlineStatus.Items.Count - 1;
listBoxOnlineStatus.ClearSelected();
}
}
}
}
SyncChatServer
----------MainForm.cs---------------------
using System;
using System.Collections.Generic;
using System.Windows.Forms;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SyncChatServer
{
public partial class MainForm : Form
{
/// <summary>保存连接的所有用户</summary>
private List<User> userList = new List<User>();
/// <summary>使用的本机IP地址</summary>
IPAddress localAddress;
/// <summary>监听端口</summary>
private const int port = 51888;
private TcpListener myListener;
/// <summary>是否正常退出所有接收线程</summary>
bool isNormalExit = false;
public MainForm()
{
InitializeComponent();
listBoxStatus.HorizontalScrollbar = true;
IPAddress[] addrIP = Dns.GetHostAddresses(Dns.GetHostName());
localAddress = addrIP[0];
buttonStop.Enabled = false;
}
/// <summary>【开始监听】按钮的Click事件</summary>
private void buttonStart_Click(object sender, EventArgs e)
{
myListener = new TcpListener(localAddress, port);
myListener.Start();
AddItemToListBox(string.Format("开始在{0}:{1}监听客户连接", localAddress, port));
//创建一个线程监听客户端连接请求
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
buttonStart.Enabled = false;
buttonStop.Enabled = true;
}
/// <summary>接收客户端连接</summary>
private void ListenClientConnect()
{
TcpClient newClient = null;
while (true)
{
try
{
newClient = myListener.AcceptTcpClient();
}
catch
{
//当单击“停止监听”或者退出此窗体时AcceptTcpClient()会产生异常
//因此可以利用此异常退出循环
break;
}
//每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息
User user = new User(newClient);
Thread threadReceive = new Thread(ReceiveData);
threadReceive.Start(user);
userList.Add(user);
AddItemToListBox(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint));
AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count));
}
}
/// <summary>
/// 处理接收的客户端数据
/// </summary>
/// <param name="userState">客户端信息</param>
private void ReceiveData(object userState)
{
User user = (User)userState;
TcpClient client = user.client;
while (isNormalExit == false)
{
string receiveString = null;
try
{
//从网络流中读出字符串,此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串
receiveString = user.br.ReadString();
}
catch
{
if (isNormalExit == false)
{
AddItemToListBox(string.Format("与[{0}]失去联系,已终止接收该用户信息", client.Client.RemoteEndPoint));
RemoveUser(user);
}
break;
}
AddItemToListBox(string.Format("来自[{0}]:{1}", user.client.Client.RemoteEndPoint, receiveString));
string[] splitString = receiveString.Split(',');
switch (splitString[0])
{
case "Login":
user.userName = splitString[1];
SendToAllClient(user, receiveString);
break;
case "Logout":
SendToAllClient(user, receiveString);
RemoveUser(user);
return;
case "Talk":
string talkString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2);
AddItemToListBox(string.Format("{0}对{1}说:{2}",
user.userName, splitString[1], talkString));
SendToClient(user, "talk," + user.userName + "," + talkString);
foreach (User target in userList)
{
if (target.userName == splitString[1] && user.userName != splitString[1])
{
SendToClient(target, "talk," + user.userName + "," + talkString);
break;
}
}
break;
default:
AddItemToListBox("什么意思啊:" + receiveString);
break;
}
}
}
/// <summary>
/// 发送message给user
/// </summary>
/// <param name="user">指定发给哪个用户</param>
/// <param name="message">信息内容</param>
private void SendToClient(User user, string message)
{
try
{
//将字符串写入网络流,此方法会自动附加字符串长度前缀
user.bw.Write(message);
user.bw.Flush();
AddItemToListBox(string.Format("向[{0}]发送:{1}",
user.userName, message));
}
catch
{
AddItemToListBox(string.Format("向[{0}]发送信息失败",
user.userName));
}
}
/// <summary>发送信息给所有客户</summary>
/// <param name="user">指定发给哪个用户</param>
/// <param name="message">信息内容</param>
private void SendToAllClient(User user, string message)
{
string command = message.Split(',')[0].ToLower();
if (command == "login")
{
for (int i = 0; i < userList.Count; i++)
{
SendToClient(userList[i], message);
if (userList[i].userName != user.userName)
{
SendToClient(user, "login," + userList[i].userName);
}
}
}
else if(command=="logout")
{
for (int i = 0; i < userList.Count; i++)
{
if (userList[i].userName != user.userName)
{
SendToClient(userList[i], message);
}
}
}
}
/// <summary>移除用户</summary>
/// <param name="user">指定要删除的用户</param>
private void RemoveUser(User user)
{
userList.Remove(user);
user.Close();
AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count));
}
private delegate void AddItemToListBoxDelegate(string str);
/// <summary>在ListBox中追加状态信息</summary>
/// <param name="str">要追加的信息</param>
private void AddItemToListBox(string str)
{
if (listBoxStatus.InvokeRequired)
{
AddItemToListBoxDelegate d = AddItemToListBox;
listBoxStatus.Invoke(d, str);
}
else
{
listBoxStatus.Items.Add(str);
listBoxStatus.SelectedIndex = listBoxStatus.Items.Count - 1;
listBoxStatus.ClearSelected();
}
}
/// <summary>【停止监听】按钮的Click事件</summary>
private void buttonStop_Click(object sender, EventArgs e)
{
AddItemToListBox("开始停止服务,并依次使用户退出!");
isNormalExit = true;
for (int i = userList.Count - 1; i >= 0; i--)
{
RemoveUser(userList[i]);
}
//通过停止监听让myListener.AcceptTcpClient()产生异常退出监听线程
myListener.Stop();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}
/// <summary>关闭窗口时触发的事件</summary>
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (myListener != null)
{
//引发buttonStop的Click事件
buttonStop.PerformClick();
}
}
}
}
//-------------User.cs----------------//
using System.Net.Sockets;
using System.IO;
namespace SyncChatServer
{
class User
{
public TcpClient client{get; private set;}
public BinaryReader br{get; private set;}
public BinaryWriter bw{get; private set;}
public string userName {get; set; }
public User(TcpClient client)
{
this.client = client;
NetworkStream networkStream = client.GetStream();
br = new BinaryReader(networkStream);
bw = new BinaryWriter(networkStream);
}
public void Close()
{
br.Close();
bw.Close();
client.Close();
}
}
}
- 聊天工具
- 聊天工具
- 聊聊 聊天工具
- 局域网聊天工具
- 办公室聊天工具
- Web聊天工具
- 局域网聊天工具
- 局域网聊天工具
- 局域网聊天工具
- UDP聊天工具
- 即时聊天工具
- 网络聊天工具
- 聊天工具 客户端
- 聊天工具服务器
- 蓝牙聊天工具
- 局域网聊天工具
- Tox 聊天工具
- 网络聊天工具的实现
- 图像特征简介
- xen 添加hypercall
- 网络游戏demo开发实例:多人在线RPG游戏(MMO RPG)demo的开发记录(第17篇下)
- Hessian学习
- 转android Reflection 反射
- 聊天工具
- iBatis中易混概念isNull isEmpty isNotNull isNotEmpty
- 文件信息批量导入数据库(Struts2实现文件上传,POI实现Excel文件读取并写入数据库) .
- 分治_数列最大值
- 总结一下基于s3c2440开发板进行开发的一些流程
- BIEE 之 介绍变量与请求变量
- 关于openGL, openGL ES, openVG及android中2D调用关系的报告
- 对自己大学专业学习的期望
- GCC链接脚本