也就服务器不一样的写法,弄了一个类似于Map的容器,其实是字典数组的感觉,客户端和原来一样
服务端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Server2
{
public partial class Server : Form
{
public Server()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
Thread threadWatch = null;
Socket socketWatch = null;
private void SendServer_Click(object sender, EventArgs e)
{
socketWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
int port = Convert.ToInt32(Port.Text.Trim());
IPAddress ip = IPAddress.Parse(IP.Text.Trim());
IPEndPoint ipe = new IPEndPoint(ip, port);
socketWatch.Bind(ipe);
socketWatch.Listen(5);
threadWatch = new Thread(WatchConnect);
threadWatch.IsBackground = true;
threadWatch.Start();
Message.AppendText("服务器已经启动,开始监听..." + "\r\n");
}
//感觉和C++的Map一样的一个容器
Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
Socket socketConnect = null;//与客户端建立连接的套接字
string clientName = null;//访问者的名字
IPAddress clientIP;//访问者的IP
int clientPort;//访问者的端口号
private void WatchConnect()
{
while (true)
{
try
{
socketConnect = socketWatch.Accept();
}
catch (Exception ex)
{
Message.AppendText(ex.Message);
break;
}
clientIP = (socketConnect.RemoteEndPoint as IPEndPoint).Address;//获取访问者的IP
clientPort = (socketConnect.RemoteEndPoint as IPEndPoint).Port;//获取访问者的Port
//创建访问者的标识,IP + Port
clientName = "IP:" + clientIP + "Port:" + clientPort