socket服务器代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Sockets;
using System.Net;
using System.Threading;
namespace socket
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Socket ServerSocket = null;
private void btnStart_Click(object sender, RoutedEventArgs e)
{
//将IP地址和端口号绑定到网络节点point上
IPEndPoint IPE = new IPEndPoint(IPAddress.Parse(tboxIP.Text), Int32.Parse(tboxPort.Text));
//实例化套接字
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定端口
ServerSocket.Bind(IPE);
//SOCket开始倾听
ServerSocket.Listen(10);
showmsg("服务器已启动,监听中...");
//创建线程
Thread thread = new Thread(ListenClientConnect);
//后台线程
thread.IsBackground=true;
//线程开始
thread.Start();
}
//创建一个字典集合
Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
private void ListenClientConnect(object obj)
{
while (true)
{
//接收来自客户端信息
Socket socketClient = ServerSocket.Accept();
//把客户端IP装换为字符串
string RemoteIP = socketClient.RemoteEndPoint.ToString();
//字典集合添加IP
dic.Add(RemoteIP, socketClient);
//委托添加IP
Dispatcher.Invoke(()=>lstboxIP.Items.Add(RemoteIP));
showmsg(RemoteIP + "已连接");
//创建接受信息线程
Thread recieveThread = new Thread(recievemsg);
//线程为后台线程
recieveThread.Is