基本信息
源码名称:C# 简易聊天软件(socket编程)
源码大小:0.62M
文件格式:.rar
开发语言:C#
更新时间:2017-06-11
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SyncChatServer//================================服务器
{
public partial class Form1 : Form
{
//保存用户列表
private List<User> userList = new List<User>();
//监听socket
private Socket myListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
private bool isNormalExit = false;
//端口号
private static int myprot = 8889;
//用户人数
private static int usercount = 0;
public Form1()
{
InitializeComponent();
button2.Enabled=false;
IPEndPoint ep;
IPAddress ip = IPAddress.Parse("127.0.0.1");
try
{
myListener.Bind(new IPEndPoint(ip, myprot));
richTextBox1.AppendText("主机IP:" ip.ToString() "\n");
}
catch {
richTextBox1.AppendText("绑定失败");
}
//===================================================
}
//-------------------------------------------向窗口输出信息
private delegate void buttu_richBoxDelegate(string message);
private void buttu_richBox(string message)
{
richTextBox1.AppendText(message "\n");
}
//=======================================================
//-------------------------------------------------------监听按键
private void button1_Click(object sender, EventArgs e)
{
isNormalExit = false;
buttu_richBoxDelegate d=buttu_richBox;
try
{
myListener.Listen(10);
richTextBox1.Invoke(d,"成功监听.");
}catch{
richTextBox1.Invoke(d,"监听失败。");
}
Thread mhThread=new Thread(ListenClientConnect);
mhThread.IsBackground=true;
mhThread.Start();
button1.Enabled=false;
button2.Enabled=true;
}
//=======================================================
//-------------------------------------------------------监听事件
private void ListenClientConnect()
{
Socket newClient =null;
while(isNormalExit==false)
{
try
{
newClient=myListener.Accept();
if (isNormalExit == true)
{
newClient.Close();
usercount = 0;
UserCount(usercount);
break;
}
}
catch
{
break ;
}
User user = new User(newClient);
Thread threadReceive = new Thread(ReceiveData);
threadReceive.IsBackground=true;
threadReceive.Start(user);
UserCount( usercount);
}
}
//=======================================================
//-------------------------------------------------------接收信息函数
private void ReceiveData(object userState)
{
User user =(User)userState;
Socket client=user.client;
byte[] result=new byte[2048];
string receiveString = null;
int receiveNumber;
while(isNormalExit==false)
{
try
{
receiveNumber = client.Receive(result);
receiveString=Encoding.UTF8.GetString(result,0,receiveNumber);
//sendMessageTorichBox(receiveString);
}
catch
{
if(isNormalExit==false)
{
sendMessageTorichBox("用户" user.username "已经退出!");
RemoveUser(user);
}
break;
}
string[] splitString =receiveString.Split(',');
switch(splitString[0].ToLower())
{
case "login":
user.username=splitString[1];
user.ip = splitString[2];
user.port = int.Parse(splitString[3]);
userList.Add(user);
AddItemToListBox(user.username);
sendToAllClient(user,receiveString);
FirstLogin(user);
break;
case "logout":
DeletItemInListBox(user.username);
sendToAllClient(user,receiveString);
RemoveUser(user);
UserCount(--usercount);
break;
case "talk":
multMessage(user,receiveString);
break;
default:
sendMessageTorichBox("不知道什么意思!");
break;
}
}
}
//=============================================================
private void multMessage(User user,String receiveString)
{
string[] splitString = receiveString.Split(',');
for(int i=1;i<splitString.Length;i=i 3)
{
sendMessageTorichBox(string.Format("[{0}] 对 [{1}] 说:", user.username, splitString[i]) splitString[i 1]);
foreach (User target in userList)
{
if (target.username == splitString[i] && user.username != splitString[i])
{
SendToClient(target, "talk," user.username "," splitString[i 1]);
break;
}
}
}
}
//=============================================================
private void SendToClient(User user,string message)
{
button_richBoxDelegate d=button_richBox;
Socket socket=user.client;
try
{
socket.Send(Encoding.UTF8.GetBytes(message));
}
catch
{
richTextBox1.Invoke(d,"发送信息失效。");
}
}
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 ",");
}
}
else if(command=="logout")
{
for(int i=0;i<userList.Count;i )
{
if(userList[i].username!=user.username)
{
SendToClient(userList[i],message);
}
}
}
}
private void FirstLogin(User user)
{
for (int i = 0; i < userList.Count; i )
{
if(userList[i].username!=user.username)
{
SendToClient(user,"login," userList[i].username "," userList[i].ip "," userList[i].port ",");
}
}
}
private delegate void UserCountDelegate(object obj);
private void UserCount(object obj)
{
UserCountDelegate d = userCountFunction;
label3.Invoke(d,obj);
}
private void userCountFunction(object obj)
{
label3.Text = (int)obj " 人";
}
private void RemoveUser(User user)
{
userList.Remove(user);
user.Close();
}
private delegate void button_richBoxDelegate(string str);
private void sendMessageTorichBox(string str)
{
button_richBoxDelegate d=button_richBox;
richTextBox1.Invoke(d,str);
}
private void button_richBox(string str)
{
richTextBox1.AppendText(str "\n");
}
private delegate void DeletItem_ListBoxDelegate(string str);
private void DeletItemInListBox(string str)
{
DeletItem_ListBoxDelegate d = DeletItem_ListBox;
listBox1.Invoke(d,str);
}
private void DeletItem_ListBox(string str)
{
listBox1.Items.Remove(str);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.ClearSelected();
}
private delegate void AddItem_ListBoxDelegate(string str);
private void AddItemToListBox(string str)
{
AddItem_ListBoxDelegate d=AddItem_ListBox;
listBox1.Invoke(d,str);
}
private void AddItem_ListBox(string str)
{
listBox1.Items.Add(str);
listBox1.SelectedIndex=listBox1.Items.Count-1;
listBox1.ClearSelected();
}
private void button2_Click(object sender, EventArgs e)
{
sendMessageTorichBox("正在停止服务器,并依次使用户退出!");
isNormalExit=true;
for(int i=userList.Count-1;i>=0;i--)
{
userList[i].client.Close();
RemoveUser(userList[i]);
}
//myListener.Shutdown(SocketShutdown.Both);
//myListener.Close();
button1.Enabled=true;
button2.Enabled=false;
CloseConnect();
//mhThread.Join();
}
private delegate void AddrichTextBox1MassageDelegate(string str);
private void sendrichTextBox1Massage(string str)
{
richTextBox1.AppendText(str "\n");
}
private void button3_Click(object sender, EventArgs e)
{
AddrichTextBox1MassageDelegate d = sendrichTextBox1Massage;
if (listBox1.SelectedIndex != -1)
{
//SendMessage("talk," listBox1.SelectedItem "," textBox2.Text);
//----------------------------------------------------
if (listBox1.Items.Count > 0)
{
for (int i = 0; i < listBox1.SelectedItems.Count; i )
{
for (int j = 0; j < userList.Count; j )
{
if (userList[j].username == listBox1.SelectedItems[i].ToString())
{
SendToClient(userList[j], "talk,Server," textBox1.Text);
richTextBox1.Invoke(d, "[Server] 对 [" userList[j].username "]说:" textBox1.Text);
}
}
//SendMessage("talk," listBox1.SelectedItems[i].ToString() "," textBox2.Text);
//richTextBox1.Invoke(d, "我对[" listBox1.SelectedItems[i].ToString() "]说:" textBox2.Text);
}
}
//----------------------------------------------------
/*for(int i=0;i<userList.Count;i )
{
if(userList[i].username == listBox1.SelectedItem.ToString())
{
SendToClient(userList[i], "talk,Server," textBox1.Text);
richTextBox1.Invoke(d, "[Server] 对 [" userList[i].username "]说:" textBox1.Text);
textBox1.Clear();
}
}*/
textBox1.Clear();
}
else
{
sendrichTextBox1Massage("请先选择一个对话者.");
}
}
private delegate void ClearListBoxItemDelegate();
private void CloseConnect()
{
ClearListBoxItemDelegate d1 = ClearListBoxItemFunction;
listBox1.Invoke(d1);
usercount = 0;
UserCount(usercount);
}
private void ClearListBoxItemFunction()
{
listBox1.Items.Clear();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}