C#socket网络编程
私聊,群聊,文件传输
ChatRoomServer服务端代码
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text;
using System.Windows.Forms; using System.Net;
using System.Threading; using System.Net.Sockets; using System.Diagnostics;
namespace ChatRoomServer {
publicpartialclassChatRoomServer : Form {
public ChatRoomServer() {
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; }
Dictionary
string hName = \;
foreach (KeyValuePair
hName += a.Value + \; } return hName;
}
privatevoid FConnectClint(object cSocket) {
bool flag = true;
Socket CliSocket = (Socket)cSocket; try
{
NetworkStream receive = newNetworkStream(CliSocket); while (flag && StartServerBool) {
Byte[] byt_redata = newByte[1024 * 1024];
int ByteLength = receive.Read(byt_redata, 0, byt_redata.Length); Array.Resize(ref byt_redata, ByteLength);
string str_redata = Encoding.Unicode.GetString(byt_redata); if (str_redata.Contains(\)) {
string ClientName = str_redata.Replace(\, \); DictionaryClient.Add(CliSocket, ClientName);
textBox3.Text += DateTime.Now.ToString(\年¨oMM月?dd日¨? HH:mm:ss\) + \用??户??:êo\ + ClientName + \加¨?入¨?聊¢?天?¨?\ + Environment.NewLine; foreach (KeyValuePair
NetworkStream wrterJoin = newNetworkStream(a.Key); if (a.Value != ClientName) {
Byte[] bytWrterJoin = Encoding.Unicode.GetBytes((\ + ClientName)); wrterJoin.Write(bytWrterJoin, 0, bytWrterJoin.Length); } else
{
Byte[] bytWrterList = Encoding.Unicode.GetBytes((\ + GetClientName())); wrterJoin.Write(bytWrterList, 0, bytWrterList.Length); }
}
}
if (str_redata.Contains(\)) {
foreach (KeyValuePair
NetworkStream wrterChatAll = newNetworkStream(a.Key);
Byte[] BytwrterChatAll = Encoding.Unicode.GetBytes(str_redata); wrterChatAll.Write(BytwrterChatAll, 0, BytwrterChatAll.Length); wrterChatAll.Close(); } }
if (str_redata.Contains(\)) {
string StrMesg = str_redata.Replace(\, \); string ClientName = DictionaryClient[CliSocket];
string ClientName2 = StrMesg.Split(newstring[] { \ }, StringSplitOptions.None)[0]; string SayMesg = StrMesg.Split(newstring[] { \ }, StringSplitOptions.None)[1]; foreach (KeyValuePair
NetworkStream wrterChatToOne = newNetworkStream(a.Key); Byte[] BytChatToOne = Encoding.Unicode.GetBytes((\ + ClientName + \ + SayMesg));
wrterChatToOne.Write(BytChatToOne, 0, BytChatToOne.Length); wrterChatToOne.Close(); break;
} } }
if (str_redata.Contains(\)) {
string StrMesg = str_redata.Replace(\, \); string ClientName = DictionaryClient[CliSocket];
string ClientName2 = StrMesg.Split(newstring[] { \ }, StringSplitOptions.None)[0];
string SayMesg = StrMesg.Split(newstring[] { \ }, StringSplitOptions.None)[1]; foreach (KeyValuePair
NetworkStream wrterChatToOne = newNetworkStream(a.Key);
Byte[] BytChatToOne = Encoding.Unicode.GetBytes((\ + ClientName + \ + SayMesg));
wrterChatToOne.Write(BytChatToOne, 0, BytChatToOne.Length); wrterChatToOne.Close(); break;
} } }