您的位置:首页 > 其它

使用socket模拟服务器给客户端发消息

2015-03-27 15:36 246 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace service
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

}

Thread threadWatch = null;
Socket Mysocket = null;
//接受缓存
byte[] arrMsgRec = new byte[1024 * 1024 * 2];
Socket policy = null;
Dictionary<string, Socket> SoketList = new Dictionary<string, Socket>();
Thread threadRece = null;
private void WatchConnection()
{

showMessage("等待客户连接");

while (true)
{
policy = Mysocket.Accept();
Socket policynew = policy;
showMessage("连接成功");

ListBox ClientListbox = ClientListboxs;
ClientListbox.Dispatcher.Invoke(new Action(() => { ClientListbox.Items.Add(policynew.RemoteEndPoint.ToString()); }));

SoketList.Add(policynew.RemoteEndPoint.ToString(), policy);
if (threadRece == null)
{
threadRece = new Thread(Rece);
threadRece.IsBackground = true;
threadRece.Start();
}
}

}
/// <summary>
/// 只能
/// </summary>
private void Rece()
{
while (true)
{
int strlong = policy.Receive(arrMsgRec);

string strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, strlong);
showMessage(strMsgRec);
}
}
private void StartSocket()
{
//创建监听套接字
Mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取ip对象
IPAddress address = IPAddress.Parse("192.168.1.54");
//创建IP和端口
IPEndPoint endpoint = new IPEndPoint(address, int.Parse("8080"));
Mysocket.Bind(endpoint);
//监听队列长度
Mysocket.Listen(10);
threadWatch = new Thread(WatchConnection);
threadWatch.IsBackground = true;
threadWatch.Start();

}
private void showMessage(string msg)
{
Action action = () => MsgContent.AppendText(msg+"\r\n");
if (System.Threading.Thread.CurrentThread !=
MsgContent.Dispatcher.Thread)
{
MsgContent.Dispatcher.Invoke
(System.Windows.Threading.DispatcherPriority.Normal,
action);
}
else
{
action();
}

}

private void start_Click_1(object sender, RoutedEventArgs e)
{
StartSocket();
}

//显示发送的历史消息
//public void Sends()
//{
//    string Msg = MsgContent1.Text;
//    byte[] btMsg = System.Text.Encoding.UTF8.GetBytes(Msg);
//    Mysocket.Send(btMsg);
//    showMessage("发送:" + Msg);

//}
private void send(object sender, RoutedEventArgs e)
{
policy.Send(System.Text.Encoding.UTF8.GetBytes(MsgContext.Text));
//  Sends();
MsgContext.Text = "";
}

ListBox ClientListboxs = null;
private void LoadGrid(object sender, RoutedEventArgs e)
{
Grid grid = sender as Grid;
foreach (var child in grid.Children)
{
if (child is ListBox)
{
if ((child as ListBox).Name == "ClientListbox")
ClientListboxs = child as ListBox;
}
}
}
private void ClientListbox_Selected_1(object sender, SelectionChangedEventArgs e)
{
ListBox ClientListbox = ClientListboxs;
string clientSelected = ClientListbox.SelectedItem.ToString();
policy = SoketList[clientSelected];
}

private void MsgContext_TextChanged(object sender, TextChangedEventArgs e)
{
// sendMsg.Enabled = MsgContext.Text.Trim() != String.Empty;

}

}
}


以上是服务器端代码,下面是客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace Barrage
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
///
public partial class MainWindow : Window
{
Thread BarrageThread = null;

public MainWindow()
{
InitializeComponent();
Connect.Click += (o, s) => { client(); };
// client();

}

string firsttxt = "弹幕测试中";

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Left = 0.0;
this.Top = 0.0;
this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;

BarrageThread = new Thread(() =>
{
for (int i = 0; i < 105; )
{
Random rd = new Random();

//SetBarrage("上海思来氏信息咨询有限公司欢迎你".PadLeft(rd.Next(5, 30), '啦'), i);
SetBarrage("" + firsttxt + "".PadLeft(rd.Next(5, 10), '啦'), i);
if (i == 104) { i = 0; } else { i++; }

System.Threading.Thread.Sleep(240);
}
});

BarrageThread.Start();
}

public void SetBarrage(string content, int img)
{
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
Dictionary<object, double> ldi = new Dictionary<object, double>();

int lines = (Convert.ToInt32(this.Height) -100) / 2;
int line = 1;

Random rd = new Random();
for (int i = 0; i < lines; i++) { ldi.Add(i, 0); }

//foreach (StackPanel item in canvas.Children)
//{
//    if (ldi.ContainsKey(item.Tag))
//    {
//        if (ldi[item.Tag] < Convert.ToDouble(item.GetValue(Canvas.LeftProperty)))
//        {
//            ldi[item.Tag] = Convert.ToDouble(item.GetValue(Canvas.LeftProperty));
//        }
//    }
//    else
//    {
//        ldi.Add(item.Tag, Convert.ToDouble(item.GetValue(Canvas.LeftProperty)));
//    }
//}

if (ldi.Count(m => m.Value == 0) > 1)
{
var list = ldi.Where(m => m.Value == 0).ToList();

line = Convert.ToInt32(list[rd.Next(0, list.Count)].Key);
}
else
{
line = Convert.ToInt32(ldi.OrderBy(m => m.Value).FirstOrDefault().Key);
}

#region StackPanel
StackPanel sp = new StackPanel();
//调整行高与行距
sp.Tag = line;
sp.Orientation = Orientation.Horizontal;
sp.SetValue(Canvas.LeftProperty, this.Width);
sp.SetValue(Canvas.TopProperty, Convert.ToDouble(40* line) + 1);

TextBlock tb = new TextBlock();

tb.VerticalAlignment = System.Windows.VerticalAlignment.Center;
//调整字体大小
tb.FontSize = 20;
tb.Text = content;
//调整字体颜色
tb.Foreground = new SolidColorBrush(Color.FromRgb(
Convert.ToByte(rd.Next(0, 255)),
Convert.ToByte(rd.Next(0, 255)),
Convert.ToByte(rd.Next(0, 255))));

sp.Children.Add(tb);

GifImage gi = new GifImage();
//字体后面添加表情
gi.Width = 24;
gi.Height =24;
gi.Source = "images/e" + (img + 100) + ".gif";

sp.Children.Add(gi);

canvas.Children.Add(sp);

//TimeSpan.FromSeconds(20) 调整滚动速度
DoubleAnimation animation =
new DoubleAnimation(this.Width, -this.Width, new Duration(TimeSpan.FromSeconds(20)));

animation.Completed += new EventHandler((object o, EventArgs arg) =>
{
canvas.Children.Remove(sp);
});

sp.BeginAnimation(Canvas.LeftProperty, animation);

#endregion
}));
}
protected override void OnClosed(EventArgs e)
{
BarrageThread.Abort();

base.OnClosed(e);

Application.Current.Shutdown();
}
//  Socket 接受服务器响应
Socket Mysocket = null;
byte[] arrMsgRec = new byte[1024 * 1024 * 2];
public void client()
{
Mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取ip对象
IPAddress address = IPAddress.Parse("192.168.1.54");
//创建IP和端口
IPEndPoint endpoint = new IPEndPoint(address, int.Parse("8080"));

Mysocket.Connect(endpoint);
Thread threadWatch = new Thread(ReceiveMsg);
threadWatch.IsBackground = true;
threadWatch.Start();

}
//接收信息
public void ReceiveMsg()
{
while (true)
{

int strlong = Mysocket.Receive(arrMsgRec);

string strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, strlong);
// strMsgRec = firsttxt;
firsttxt = strMsgRec;
showMessage(firsttxt);
}
}
//显示信息
private void showMessage(string msg)
{
Action action = () => MsgContent.AppendText(msg + "\r\n");
if (System.Threading.Thread.CurrentThread !=
MsgContent.Dispatcher.Thread)
{
MsgContent.Dispatcher.Invoke
(System.Windows.Threading.DispatcherPriority.Normal,
action);
}
else
{
action();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐