在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Reflection; namespace ConsoleApplication1 { public class Program { Thread[] SocketThreadList = new Thread[100]; static Socket TCPListen = null; static void Main(string[] args) { TCPListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint LocalPort = new IPEndPoint(IPAddress.Any, 55000); TCPListen.Bind(LocalPort); TCPListen.Listen(100); Thread AcceptThread = new Thread(new ThreadStart(AcceptWorkThread)); AcceptThread.Start(); Console.WriteLine("****** 软创通信服务器程序 ******"); Console.WriteLine(string.Format("开始监听 <{0}>", LocalPort)); Console.WriteLine("单击回车键退出SOCKET"); Console.ReadLine(); GC.Collect(); GC.WaitForPendingFinalizers(); } // 接收连接线程 [STAThread] static void AcceptWorkThread() { // 指示为后台线程 Thread.CurrentThread.IsBackground = true; while (true) { // 为新建连接创建新的Socket实例 Socket s_Accept = TCPListen.Accept(); IPEndPoint remoteAddress = (IPEndPoint)s_Accept.RemoteEndPoint; Console.WriteLine(string.Format("接收到来自 {0} 的连接", remoteAddress)); // 接收数据专用线程 Thread ReceiveThread = new Thread(new ParameterizedThreadStart(ReceiveWorkThread)); ReceiveThread.Start(s_Accept); Thread.Sleep(100); } } static void ReceiveWorkThread(object obj) { Thread.CurrentThread.IsBackground = true; // 标识后台线程 Socket s_Receive = (Socket)obj; byte[] buffer = new byte[1024]; // 创建接收缓冲 IPEndPoint remoteAddress = (IPEndPoint)s_Receive.RemoteEndPoint; try { while (s_Receive.Connected) { if (s_Receive.Connected) { int ReceiveCount = s_Receive.Receive(buffer); Console.WriteLine(string.Format("{0}:{1}", remoteAddress, Encoding.Default.GetString(buffer))); // 返回接收成功数据 s_Receive.Send(Encoding.Default.GetBytes("AAA")); Thread.Sleep(100); } else { s_Receive.Close(); break; } } } catch { Console.WriteLine(string.Format("{0} 断开连接", remoteAddress)); } } } } |
请发表评论