tcp实现类 internal class TcpServer { public Socket ServerSocket { get; set; } public D
tcp实现类
internal class TcpServer { public Socket ServerSocket { get; set; } public Dictionary<string,Socket> Sockets { get; set; }= new Dictionary<string,Socket>(); public byte[] SendBuffer { get; set; } public byte[] ReceiveBuffer { get; set; } /// /// 创建构造函数 /// /// /// public TcpServer(int sendBufferLength, int receiveBufferLength) { SendBuffer = new byte[sendBufferLength]; ReceiveBuffer = new byte[receiveBufferLength]; } /// /// 启动服务器 /// /// /// public void Start(string ip, string port) { ServerSocket = CreateSocket(ip, port); CreateThread(); } /// /// 服务端向指定客户端发送消息 /// /// /// public void Send(string clientInfo, byte[] data) { Socket socket = Sockets[clientInfo]; socket.Send(data); } /// /// 创建服务端Socket /// /// /// /// private Socket CreateSocket(string ip, string port) { Socket socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address=IPAddress.Parse(ip); IPEndPoint endPoint=new IPEndPoint(address, int.Parse(port)); socket.Bind(endPoint); socket.Listen(20); return socket; } /// /// 创建监听客户端的线程并启动 /// private void CreateThread() { Thread watchThread = new Thread(WatchConnection); watchThread.IsBackground = true; watchThread.Start(); } /// /// 监听客户端请求 /// private void WatchConnection() { while (true) { Socket clientSocket = null; try { clientSocket = ServerSocket.Accept(); IPEndPoint endPoint = (IPEndPoint)clientSocket.RemoteEndPoint; string ip= endPoint.Address.ToString(); string port= endPoint.Port.ToString(); Sockets.Add(ip + ":" + port, clientSocket); } catch (Exception ex) { Console.WriteLine(ex.ToString()); break; } ParameterizedThreadStart pts = new ParameterizedThreadStart(ClientReceiver); Thread clientThread = new Thread(pts); clientThread.IsBackground = true; clientThread.Start(clientSocket); } } /// /// /// /// private void ClientReceiver(object socket) { Socket clientSocket=socket as Socket; int ReceiveBufferSize = 1 * 1024; while (true) { int receivedLength = 0; byte[] buffer = new byte[ReceiveBufferSize]; try { List<byte> ls = new List<byte>(); if (clientSocket != null) { receivedLength = clientSocket.Receive(buffer); if (receivedLength > 0) {Buffer.BlockCopy(buffer,0, ReceiveBuffer, 0, receivedLength);string msg = "Receive Success " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");byte[] datas = System.Text.Encoding.UTF8.GetBytes(msg);clientSocket.Send(datas); } } }catch(Exception ex) { Console.WriteLine(ex.ToString()); break; } } } }
页面布局
<Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="50"/> <RowDefinition Height="50"/> <RowDefinition Height="50"/> <RowDefinition Height="*"/> <RowDefinition Height="50"/> <RowDefinition Height="50"/> </Grid.RowDefinitions> <TextBlock Grid.Row="0" Text="配置" VerticalAlignment="Center"/> <DockPanel Grid.Row="1"> <DockPanel HorizontalAlignment="Left"> <TextBlock Text="地址" VerticalAlignment="Center" Margin="20 0 10 0"/> <TextBox x:Name="TextBoxIp" Text="" Width="100" Height="36" VerticalContentAlignment="Center"/> <TextBlock Text="端口" VerticalAlignment="Center" Margin="20 0 10 0"/> <TextBox x:Name="TextBoxport" Text="" Width="100" Height="36" VerticalContentAlignment="Center"/> <Button x:Name="ButtonStart" Content="启动" Width="75" Height="36" Margin="20,0,10,0" Click="ButtonStart_Click"/> </DockPanel> <DockPanel HorizontalAlignment="Right"> <TextBlock Text="客户端" VerticalAlignment="Center" Margin="20 0 10 0"/> <ComboBox x:Name="ComboBoxClient" SelectedValuePath="Key" DisplayMemberPath="Key" Width="200" Height="36" Margin="20 0 10 0" SelectionChanged="ComboBoxClient_SelectionChanged"/> </DockPanel> </DockPanel> <TextBlock Grid.Row="2" Text="接收" VerticalAlignment="Center"/> <TextBox Grid.Row="3" Name="TextBoxReciver" Text=""/> <TextBlock Grid.Row="4" Text="发送" VerticalAlignment="Center"/> <StackPanel Grid.Row="5" Orientation="Horizontal"> <TextBox x:Name="TextBoxSender" Text="" Width="650" Height="36"/> <Button Content="发送" Click="ButtonSend_CLick" Width="75" Height="36" HorizontalAlignment="Right" Margin="10 0 20 0"/> </StackPanel> </Grid>
后台代码
TcpServer tcpServer= null; public MainWindow() { InitializeComponent(); tcpServer = new TcpServer(2 * 1024, 2 * 1024); TextBoxIp.Text = "10.11.10.44"; TextBoxport.Text = "8080"; } private void ButtonStart_Click(object sender, RoutedEventArgs e) { string address = this.TextBoxIp.Text; string[] arr= address.Split('.'); if (arr.Length == 4) { foreach(string item in arr) { int i=int.Parse(item); if(i < 0 || i > 255) { return; } } } string port = this.TextBoxport.Text; int j= int.Parse(port); if (j < 0) { return; } ComboBoxClient.ItemsSource = tcpServer.Sockets; tcpServer.Start(address, port); } string currentClient = null; private void ComboBoxClient_SelectionChanged(object sender, SelectionChangedEventArgs e) { //currentClient = ComboBoxClient.SelectedValue.ToString(); ComboBox comboBox = sender as ComboBox; string str = comboBox.SelectedValue.ToString(); if (tcpServer.Sockets.ContainsKey(str)) { currentClient = str; } } private void ButtonSend_CLick(object sender, RoutedEventArgs e) { if (currentClient != null) { string str = TextBoxSender.Text; byte[] bytes=System.Text.Encoding.UTF8.GetBytes(str); tcpServer.Send(currentClient,bytes); } }
运行结果
来源地址:https://blog.csdn.net/qq_27474555/article/details/131287696
--结束END--
本文标题: TCP服务器的C#实现
本文链接: https://lsjlt.com/news/392955.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0