客户端:
/// <summary>
/// 显示消息委托
/// </summary>
/// <param name="Message"></param>
public delegate void MessageHandle(object sender, string Message);
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//第一步:用指定的端口号和服务器的ip建立一个EndPoint对像;
//第二步:建立一个Socket对像;
//第三步:用socket对像的Connect()方法以上面建立的EndPoint对像做为参数,向服务器发出连接请求;
//第四步:如果连接成功,就用socket对像的Send()方法向服务器发送信息;
//第五步:用socket对像的Receive()方法接受服务器发来的信息 ;
//第六步:通信结束后一定记得关闭socket;
private int iPort = 1000;
string strHostIp = "127.0.0.1";
protected bool isTryConnection;
protected Socket socket;
protected Thread thread;
protected IPEndPoint iEndPoint;
protected event MessageHandle ShowMessage;
public MainWindow()
{
InitializeComponent();
ShowMessage += new MessageHandle(MainWindow_ShowMessage);
}
void MainWindow_ShowMessage(object sender, string Message)
{
if (!this.lMessage.Dispatcher.CheckAccess())
{
this.lMessage.Dispatcher.Invoke(new Action(() =>
{
this.lMessage.Content += Message + "\n";
}));
}
}
protected bool isClose = false;
protected void StartRecives()
{
isClose = true;
while (isClose)
{
//尝试连接
while (isTryConnection)
{
//尝试连接
//暂停2秒钟
try
{
IPAddress iAddress = IPAddress.Parse(strHostIp);
iEndPoint = new IPEndPoint(iAddress, iPort);
//创建SOCKET并连接到服务器
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(iEndPoint);
isTryConnection = false;
ShowMessage(null, "服务器连接成功!");
}
catch (ArgumentNullException e)
{
//lMessage.Content = string.Format("argumentNullException: {0}", e);
isTryConnection = true;
}
catch (SocketException e)
{
isTryConnection = true;
ShowMessage(null, "Server not found,尝试连接...");
//lMessage.Content = string.Format("SocketException:{0}", e);
}
System.Threading.Thread.Sleep(isTimeOuts);
}
if (!isTryConnection)
{
try
{
//向服务器发送消息
string strSend = string.Format("hello!This is \\{0}\\Machine send socket test", machine);
byte[] bMessage = Encoding.ASCII.GetBytes(strSend);
//发送消息
socket.Send(bMessage, bMessage.Length, 0);
isTryConnection = false;
//从服务器返回消息
string strMessageRecv = "";
byte[] bReceive = new byte[1024];
int iBytes;
iBytes = socket.Receive(bReceive, bReceive.Length, 0);
strMessageRecv += Encoding.ASCII.GetString(bReceive, 0, iBytes);
ShowMessage(null, string.Format("client get message:{0}", strMessageRecv));
//lMessage.Content = string.Format("client get message:{0}", strMessageRecv);
Thread.Sleep(5000);
}
catch (ArgumentNullException e)
{
//lMessage.Content = string.Format("argumentNullException: {0}", e);
isTryConnection = true;
}
catch (SocketException e)
{
isTryConnection = true;
//lMessage.Content = string.Format("SocketException:{0}", e);
}
}
}
}
protected string machine;
protected void CloseTh() {
if (socket != null) {
socket.Close();
}
if (thread != null) {
thread.Abort();
}
}
protected int isTimeOuts = 3000;
private void btnListening_Click(object sender, RoutedEventArgs ex)
{
this.comboBox1.IsEnabled = false;
machine = this.comboBox1.Text.Trim();
lMessage.Content = "正在监听。。";
//连接到服务器
thread = new Thread(StartRecives);
thread.IsBackground = true;
thread.Start();
this.isTryConnection = true;
}
}
}
服务器端,点对点快速
//第一步:用指定的端口号和服务器的ip建立一个EndPoint对像;
//第二步:建立一个Socket对像;
//第三步:用socket对像的Bind()方法绑定EndPoint;
//第四步:用socket对像的Listen()方法开始监听;
//第五步:接受到客户端的连接,用socket对像的Accept()方法创建新的socket对像用于和请求的客户端进行通信;
//第六步:通信结束后一定记得关闭socket;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private int iPort = 1000;
string strHostIp = "127.0.0.1";
protected Thread thread;
protected event MessageHandle ShowMessage;
private Socket socketMessage;
private Socket socket;
private bool bIsClose = false;
public MainWindow()
{
InitializeComponent();
ShowMessage += new MessageHandle(MainWindow_ShowMessage);
}
void MainWindow_ShowMessage(object sender, string Message)
{
if (!this.lMessage.Dispatcher.CheckAccess())
{
this.lMessage.Dispatcher.Invoke(new Action(() => {
this.lMessage.Text += Message + "\n";
}));
}
}
private bool isTryAccepting = false;
protected void StartThread()
{
bIsClose = true;
int count = 0;
while (bIsClose)
{
while (isTryAccepting)
{
socket.Listen(0);
socketMessage = socket.Accept();
isTryAccepting = false;
ShowMessage(this.lMessage, "与客户端建立连接!");
}
if (!isTryAccepting)
{
try
{
string strRecvMessage = "";
byte[] recvBytes = new Byte[1024];
int iBtyes;
//从客户端接受消息
iBtyes = socketMessage.Receive(recvBytes, recvBytes.Length, 0);
strRecvMessage += Encoding.ASCII.GetString(recvBytes, 0, iBtyes);
//给客户端返回信息
ShowMessage(this.lMessage, string.Format("server get message:{1}--{0}", strRecvMessage, count));
string strSendMessage = "ok!Client send message successful!";
Byte[] bSendBytes = Encoding.ASCII.GetBytes(strSendMessage);
socketMessage.Send(bSendBytes, bSendBytes.Length, 0);
count++;
}
catch
{
ShowMessage(this.lMessage, "客户断开连接!");
//客户断开连接
isTryAccepting = true;
}
}
}
if (!bIsClose)
{
CloseThread();
}
}
protected void PauseThread() {
}
protected void CloseThread() {
if(socket!=null){
socket.Close();
socket = null;
}
if (socketMessage != null) {
socketMessage.Close();
socketMessage = null;
}
if (thread.IsAlive)
{
thread.Abort();
thread = null;
}
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
//创建ENDPOINT 对象
if (socket == null && socketMessage == null)
{
IPAddress iAddress = IPAddress.Parse(strHostIp);
IPEndPoint iEndPoint = new IPEndPoint(iAddress, iPort);
//创建socket 开始监听
//创建一个socket对像,如果用udp协议,则要用SocketType.Dgram类型的套接字
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(iEndPoint);
isTryAccepting = true;
lMessage.Text = "等待客户端连接....\n";
thread = new Thread(StartThread);
thread.IsBackground = true;
thread.Start();
}
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.bIsClose = false;
lMessage.Text = "服务器关闭服务\n";
}
protected void ShowMessageEx(string strInfo) {
if (!this.lMessage.Dispatcher.CheckAccess())
{
//this.lMessage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,new ChangeText(txtInfo), strInfo);
}
}
}
/// <summary>
/// 显示消息委托
/// </summary>
/// <param name="Message"></param>
public delegate void MessageHandle(object sender ,string Message);
}
服务器端,多用户
//第一步:用指定的端口号和服务器的ip建立一个EndPoint对像;
//第二步:建立一个Socket对像;
//第三步:用socket对像的Bind()方法绑定EndPoint;
//第四步:用socket对像的Listen()方法开始监听;
//第五步:接受到客户端的连接,用socket对像的Accept()方法创建新的socket对像用于和请求的客户端进行通信;
//第六步:通信结束后一定记得关闭socket;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private int iPort = 1000;
string strHostIp = "127.0.0.1";
protected Thread thread;
protected event MessageHandle ShowMessage;
private Socket socket;
private bool bIsClose = false;
public MainWindow()
{
InitializeComponent();
ShowMessage += new MessageHandle(MainWindow_ShowMessage);
}
void MainWindow_ShowMessage(object sender, string Message)
{
if (!this.lMessage.Dispatcher.CheckAccess())
{
this.lMessage.Dispatcher.Invoke(new Action(() => {
this.lMessage.Text += Message + "\n";
}));
}
}
private bool isTryAccepting = false;
protected void StartThread()
{
bIsClose = true;
int count = 0;
while (bIsClose)
{
Socket socketMessage = null;
while (isTryAccepting)
{
socket.Listen(5);
socketMessage = socket.Accept();
isTryAccepting = false;
ShowMessage(this.lMessage, "与客户端建立连接!");
}
if (socketMessage != null && !isTryAccepting)
{
try
{
string strRecvMessage = "";
byte[] recvBytes = new Byte[1024];
int iBtyes;
//从客户端接受消息
iBtyes = socketMessage.Receive(recvBytes, recvBytes.Length, 0);
strRecvMessage += Encoding.ASCII.GetString(recvBytes, 0, iBtyes);
//给客户端返回信息
ShowMessage(this.lMessage, string.Format("server get message:{1}--{0}", strRecvMessage, count));
string strSendMessage = "ok!Client send message successful!";
Byte[] bSendBytes = Encoding.ASCII.GetBytes(strSendMessage);
socketMessage.Send(bSendBytes, bSendBytes.Length, 0);
socketMessage.Close();
count++;
}
catch
{
if (socketMessage != null)
{
socketMessage.Close();
}
ShowMessage(this.lMessage, "客户断开连接!");
//客户断开连接
isTryAccepting = true;
}
}
else
{
isTryAccepting = true;
}
}
if (!bIsClose)
{
CloseThread();
}
}
protected void PauseThread() {
}
protected void CloseThread() {
if(socket!=null){
socket.Close();
socket = null;
}
if (thread.IsAlive)
{
thread.Abort();
thread = null;
}
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
//创建ENDPOINT 对象
if (socket == null )
{
IPAddress iAddress = IPAddress.Parse(strHostIp);
IPEndPoint iEndPoint = new IPEndPoint(iAddress, iPort);
//创建socket 开始监听
//创建一个socket对像,如果用udp协议,则要用SocketType.Dgram类型的套接字
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(iEndPoint);
isTryAccepting = true;
lMessage.Text = "等待客户端连接....\n";
thread = new Thread(StartThread);
thread.IsBackground = true;
thread.Start();
}
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.bIsClose = false;
lMessage.Text = "服务器关闭服务\n";
}
protected void ShowMessageEx(string strInfo) {
if (!this.lMessage.Dispatcher.CheckAccess())
{
//this.lMessage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,new ChangeText(txtInfo), strInfo);
}
}
}
/// <summary>
/// 显示消息委托
/// </summary>
/// <param name="Message"></param>
public delegate void MessageHandle(object sender ,string Message);
}