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();
}
}

最新文章

  1. iOS常用第三方框架大全
  2. Await, and UI, and deadlocks! Oh my!
  3. Linux下使用USB模拟ACM串口设备
  4. HTML5 &lt;a&gt;标签的ping属性用法
  5. hdu 1003 Max sum(简单DP)
  6. Android ListView自定义Adapter使用误区
  7. tc srm 632 500 (规律)
  8. yaf框架流程三
  9. 【BZOJ】【3158】千钧一发
  10. UVaLive 6628 Grachten (水题,数学)
  11. Java高阶面试问题合集
  12. 记录一次网站漏洞修复过程(三):第二轮处理(拦截SQL注入、跨站脚本攻击XSS)
  13. STL--hashtable
  14. css 悬浮框
  15. C++ 引用 &amp; 的详解
  16. 《linux 文件目录》- touch/rm/mv/cat/head/tail/cp/mkdir/chmod/chown/find/locate/which/whereis
  17. SoapUI link
  18. Typescript学习总结之泛型
  19. PHP学习笔记1
  20. NET Core 1.1 版本项目和2.0环境下的项目开发注意事项

热门文章

  1. 使用PHP连接、操纵Memcached的原理和教程
  2. build-essential
  3. Windows7 下安装ORACLE 11G(遇到的问题)
  4. ###使用phpmailer自动邮件提醒
  5. (poj)3268 Silver Cow Party 最短路
  6. Poj 1001 / OpenJudge 2951 Exponentiation
  7. C语言使用中的细节问题总结
  8. Newtonsoft.Json.dll解析json的dll文件使用
  9. windows 7 64bit 下apache php mysql 环境配置
  10. Demo学习: CellDraw