using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace MyChatRoomServer
{
public partial class 服务端 : Form
{
public 服务端()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
Thread thread = null; //执行accept方法的线程
Thread RecThread = null;//执行receive方法的线程
Socket SocketWatch = null; //全局变量 监听客户端的套接字
Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
Dictionary<string, Thread> dicthread = new Dictionary<string, Thread>();
private void btnlisten_Click(object sender, EventArgs e)
{
SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
SocketWatch.Bind(endpoint);
SocketWatch.Listen(10);
ShowMessage("服务器启动成功!!!");
thread = new Thread(SocketListen);
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// 监听客户端的方法
/// </summary>
void SocketListen()
{
while (true)
{
//创建监听客户端的套接字
Socket SocketClient = SocketWatch.Accept();
dict.Add(SocketClient.RemoteEndPoint.ToString(), SocketClient);
//创建接收客户端发来的消息的线程
RecThread = new Thread(RecMsg);
RecThread.IsBackground = true;
RecThread.Start(SocketClient);
dicthread.Add(SocketClient.RemoteEndPoint.ToString(), RecThread);
//把客户端的ip信息加到列表中
lbonline.Items.Add(SocketClient.RemoteEndPoint.ToString());
ShowMessage("客户端监听成功" + SocketClient.RemoteEndPoint.ToString());
}
}
/// <summary>
/// 显示消息
/// </summary>
/// <param name="s"></param>
public void ShowMessage(string s)
{
txtMsg.AppendText(s+ "\n");
}
/// <summary>
/// 服务端向客户端发送消息的方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
string StrSend = txtSendMsg.Text.ToString();
byte[] ByteSend = System.Text.Encoding.UTF8.GetBytes(StrSend);
string selectKey = lbonline.Text;
try
{
dict[selectKey].Send(ByteSend);
ShowMessage("服务端发送了消息" + StrSend);
}
catch (SocketException ex)
{
MessageBox.Show("还未选择要通信的客户端,请选择" + ex.ToString());
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/// <summary>
/// 服务端接收客户端消息的方法
/// </summary>
public void RecMsg(object soc)
{
while (true)
{
byte[] arrMsgRec = new byte[1024 * 1024 * 2];
Socket SocketClient = soc as Socket;
try
{
int length = SocketClient.Receive(arrMsgRec);
if (arrMsgRec[0] == 0)
{
string str= System.Text.Encoding.UTF8.GetString(arrMsgRec,1,length-1);
ShowMessage(SocketClient.RemoteEndPoint.ToString() + "说:" + str);
}
else if(arrMsgRec[0]==1)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog()== DialogResult.OK)
{
using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
{
fs.Write(arrMsgRec, 1, length - 1);
ShowMessage("文件保存成功");
}
}
}
}
catch(SocketException ex)
{
MessageBox.Show("客户端断开连接!!" + ex.ToString());
dict.Remove(SocketClient.RemoteEndPoint.ToString());
dicthread.Remove(SocketClient.RemoteEndPoint.ToString());
lbonline.Items.Remove(SocketClient.RemoteEndPoint.ToString());
break;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnSendAll_Click(object sender, EventArgs e)
{
foreach (string s in dict.Keys)
{
string StrSend = txtSendMsg.Text.ToString();
byte[] ByteSend = System.Text.Encoding.UTF8.GetBytes(StrSend);
dict[s].Send(ByteSend);
}
ShowMessage("服务端群发消息");
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace MyConnection
{
public partial class 客户端 : Form
{
public 客户端()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
Socket SocketWatch = null;
Thread thread = null;
private void btnConn_Click(object sender, EventArgs e)
{
SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(txtIp.Text.Trim());
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtport.Text.Trim()));
try
{
SocketWatch.Connect(endpoint);
ShowMessage("连接服务器端成功,可以通信");
}
catch (SocketException ex)
{
MessageBox.Show("服务器还未启动,不能连接!!!" + ex.ToString());
return;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
thread = new Thread(RecMsg);
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// 接收消息的方法
/// </summary>
public void RecMsg()
{
byte[] arrMsgRec = new byte[1024 * 1024 * 2];
while (true)
{
int length =-1;
try
{
length = SocketWatch.Receive(arrMsgRec);
string str = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, length);
ShowMessage(str);
}
catch (SocketException ex)
{
MessageBox.Show(ex.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
public void ShowMessage(string s)
{
txtMsg.AppendText(s + "\n");
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
string strMsg = txtSendMsg.Text.ToString();
byte[] byteMsg =System.Text.Encoding.UTF8.GetBytes(strMsg);
byte[] byteMsgSend = new byte[byteMsg.Length+1];
byteMsgSend[0] = 0;
Buffer.BlockCopy(byteMsg, 0, byteMsgSend, 1, byteMsg.Length);
SocketWatch.Send(byteMsgSend);
ShowMessage("我说:" + strMsg);
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = ofd.FileName;
}
}
/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendFile_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(txtFilePath.Text, FileMode.Open);
byte[] byteFile=new byte[1024*1024*2];
int length = fs.Read(byteFile, 0, byteFile.Length);
byte[] byteFIleSend = new byte[length + 1];
Buffer.BlockCopy(byteFile, 0, byteFIleSend, 1, length);
byteFIleSend[0] = 1;
SocketWatch.Send(byteFIleSend);
}
}
}