WPF下的一个Socket
public class Connection
{
Socket _connection; public Connection(Socket socket)
{
_connection = socket;
} public void WaitForSendData()
{
while (true)
{
byte[] bytes = new byte[];
string data = ""; //等待接收消息
int bytesRec = this._connection.Receive(bytes); if (bytesRec == )
{
ReceiveText("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
break;
} data += Encoding.UTF8.GetString(bytes, , bytesRec);
ReceiveText("收到消息:" + data); string sendStr = "服务端已经收到信息!";
byte[] bs = Encoding.UTF8.GetBytes(sendStr);
_connection.Send(bs, bs.Length, );
}
} public delegate void ReceiveTextHandler(string text);
public event ReceiveTextHandler ReceiveTextEvent;
private void ReceiveText(string text)
{
if (ReceiveTextEvent != null)
{
ReceiveTextEvent(text);
}
}
}
public class SocketListener
{
public Hashtable Connection = new Hashtable(); public void StartListen()
{
try
{
//端口号、IP地址
int port = ;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port); //创建一个Socket类
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(ipe);//绑定2000端口
s.Listen();//开始监听 ReceiveText("启动Socket监听..."); while (true)
{
Socket connectionSocket = s.Accept();//为新建连接创建新的Socket ReceiveText("客户端[" + connectionSocket.RemoteEndPoint.ToString() + "]连接已建立..."); Connection gpsCn = new Connection(connectionSocket);
gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText); Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn); //在新线程中启动新的socket连接,每个socket等待,并保持连接
Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
thread.Name = connectionSocket.RemoteEndPoint.ToString();
thread.Start();
}
}
catch (ArgumentNullException ex1)
{
ReceiveText("ArgumentNullException:" + ex1);
}
catch (SocketException ex2)
{
ReceiveText("SocketException:" + ex2);
}
} public delegate void ReceiveTextHandler(string text);
public event ReceiveTextHandler ReceiveTextEvent;
private void ReceiveText(string text)
{
if (ReceiveTextEvent != null)
{
ReceiveTextEvent(text);
}
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SocketListener listener;
public MainWindow()
{
InitializeComponent(); InitServer();
} private void InitServer()
{
System.Timers.Timer t = new System.Timers.Timer();
//实例化Timer类,设置间隔时间为5000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
//到达时间的时候执行事件;
t.AutoReset = true;
t.Start();
} private void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
{
if (listener != null && listener.Connection != null)
{
//label2.Content = listener.Connection.Count.ToString();
ShowText("连接数:" + listener.Connection.Count.ToString());
}
} private void button1_Click(object sender, RoutedEventArgs e)
{
Thread th = new Thread(new ThreadStart(SocketListen));
th.Start();
} private void SocketListen()
{
listener = new SocketListener();
listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
listener.StartListen();
} public delegate void ShowTextHandler(string text);
ShowTextHandler setText; private void ShowText(string text)
{
if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread)
{
if (setText == null)
{
setText = new ShowTextHandler(ShowText);
}
txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text });
}
else
{
txtSocketInfo.AppendText(text + "\n");
}
} private void button2_Click(object sender, RoutedEventArgs e)
{
ClientWindow client = new ClientWindow();
client.Show();
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SocketListener listener;
public MainWindow()
{
InitializeComponent(); InitServer();
} private void InitServer()
{
System.Timers.Timer t = new System.Timers.Timer();
//实例化Timer类,设置间隔时间为5000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
//到达时间的时候执行事件;
t.AutoReset = true;
t.Start();
} private void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
{
if (listener != null && listener.Connection != null)
{
//label2.Content = listener.Connection.Count.ToString();
ShowText("连接数:" + listener.Connection.Count.ToString());
}
} private void button1_Click(object sender, RoutedEventArgs e)
{
Thread th = new Thread(new ThreadStart(SocketListen));
th.Start();
} private void SocketListen()
{
listener = new SocketListener();
listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
listener.StartListen();
} public delegate void ShowTextHandler(string text);
ShowTextHandler setText; private void ShowText(string text)
{
if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread)
{
if (setText == null)
{
setText = new ShowTextHandler(ShowText);
}
txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text });
}
else
{
txtSocketInfo.AppendText(text + "\n");
}
} private void button2_Click(object sender, RoutedEventArgs e)
{
ClientWindow client = new ClientWindow();
client.Show();
}
}
WPF下的一个Socket的更多相关文章
- Bash Shell 下打开一个TCP / UDP SOCKET
Bash Shell 下打开一个TCP / UDP SOCKET http://jingyan.baidu.com/article/636f38bb6166c3d6b84610d1.html
- 关于一个socket在阻塞模式下是否还可以使用的实验
想到一个socket在多线程模式下,是否可以同时使用的问题,比如socket A阻塞在recv,而别的线程用socket A send是否能成功,下面上实验代码 void thread_socket( ...
- Linux下的C Socket编程 -- server端的继续研究
Linux下的C Socket编程(四) 延长server的生命周期 在前面的一个个例子中,server在处理完一个连接后便会立即结束掉自己,然而这种server并不科学啊,server应该是能够一直 ...
- Linux下的C Socket编程 -- server端的简单示例
Linux下的C Socket编程(三) server端的简单示例 经过前面的client端的学习,我们已经知道了如何创建socket,所以接下来就是去绑定他到具体的一个端口上面去. 绑定socket ...
- Linux下的C Socket编程 -- 获取对方IP地址
Linux下的C Socket编程(二) 获取域名对应的IP地址 经过上面的讨论,如果我们想要连接到远程的服务器,我们需要知道对方的IP地址,系统函数gethostbyname便能够实现这个目的.它能 ...
- Linux下的C Socket编程 -- 简介与client端的处理
Linux下的C Socket编程(一) 介绍 Socket是进程间通信的方式之一,是进程间的通信.这里说的进程并不一定是在同一台机器上也有可能是通过网络连接的不同机器上.只要他们之间建立起了sock ...
- WinForm与WPF下跨线程调用控件
Winform下: public delegate void UpadataTextCallBack(string str,TextBox text); public void UpadtaText( ...
- ZeroMQ接口函数之 :zmq_connect - 由一个socket创建一个对外连接
ZeroMQ 官方地址 :http://api.zeromq.org/4-0:zmq_connect zmq_connect(3) ØMQ Manual - ØMQ/3.2.5 Name zmq_c ...
- ZeroMQ接口函数之 :zmq_recv – 从一个socket上接收一个消息帧
ZeroMQ 官方地址 :http://api.zeromq.org/4-1:zmq_recv zmq_recv(3) ØMQ Manual - ØMQ/4.1.0 Name zmq_r ...
随机推荐
- Java的基础概念
JDK (Java Development Kit) Java Developer Kit contains tools needed to develop the Java programs, an ...
- Oracle——事务(Transaction)
事务: 事务是指作为单个逻辑工作单元执行的一组相关操作. 这些操作要求全部完成或者全部不完成. 使用事务的原因:保证数据的安全有效. 事务的四个特点:(ACID) 1.原子性(Atomic):事务中所 ...
- Java validator整理
Java validator整理 因为想对方法的入参和出参作简单的非空或者非空字符做校验,所以找了下相关的@NotNull注解 类 | 说明 --- | --- javax.validation.co ...
- JSP编程中常用的JavaScript技术(转载)
1.<tronMouseOver=this.style.backgroundColor=’#FFFFFF’ onMouseOut=this.style.backgroundColor=”> ...
- InstallShield Clone dialog
Browse to Dialogs view, right-click an existing dialog, click Clone and rename the cloned dialog. Wh ...
- ubuntu下boost的配置方法
boost版本为: boost_1_52_0ubuntu版本为:ubuntu-12.04.1-desktop-i386 这里有两种安装方法: =============第一种: 也是最简单的:进入li ...
- Linux中的安装神器--yum源安装
linux配置yum源 一.修改yum的配置文件 /etc/yum.repos.d/xxx.repo 1.进入yum配置文件目录 # cd /etc/yum.r ...
- 通过 ANE(Adobe Native Extension) 启动Andriod服务 推送消息(四)
这一节,是要把AS库和Android的jar包及相关配置文件打成一个ane包. 首先先建一个build目录,里面文件目录结构如下: 然后用打开压缩包的方式打开ServiceLib.swc, 把其中的l ...
- css3动画--超级基础知识
这么乱的笔记....供自己阅读!
- C#通过ODAC访问Oracle12c
昨天晚上刚装好Oracle12c并配制好了PLSQL Developer开发环境.今天继续完善一下,讲讲在C#中如何访问Oracle12c. 其实我们运用老早的ADO.NET也可以连接,但是在.NET ...