- 本程序可以使用ip也可以使用主机名,这样就可以在打包之后,就不需要一直动态修改IP了
服务器端代码:
public partial class FServer : Form{public FServer(){InitializeComponent();TextBox.CheckForIllegalCrossThreadCalls = false;}Thread threadWatch = null; //负责监听客户端的线程Socket socketWatch = null; //负责监听客户端的套接字private void BtnServerConn_Click(object sender, EventArgs e){bool IsContain = false;int[] num = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };int i = 0;if (txtIP.Text.Contains(num[i].ToString())){//定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//服务端发送信息 需要1个IP地址和端口号IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim()); //获取文本框输入的IP地址//将IP地址和端口号绑定到网络节点endpoint上 IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //获取文本框上输入的端口号//监听绑定的网络节点socketWatch.Bind(endpoint);//将套接字的监听队列长度限制为20socketWatch.Listen(20);//创建一个监听线程 threadWatch = new Thread(WatchConnecting);//将窗体线程设置为与后台同步threadWatch.IsBackground = true;//启动线程threadWatch.Start();//启动线程后 txtMsg文本框显示相应提示txtMsg.AppendText("开始监听客户端传来的信息!" + "\r\n");}else{//定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//服务端发送信息 需要1个IP地址和端口号//IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim()); //获取文本框输入的IP地址IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());string ic = Convert.ToString(ips[1]);IPAddress ipaddress = IPAddress.Parse(ic);//将IP地址和端口号绑定到网络节点endpoint上 IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //获取文本框上输入的端口号//监听绑定的网络节点socketWatch.Bind(endpoint);//将套接字的监听队列长度限制为20socketWatch.Listen(20);//创建一个监听线程 threadWatch = new Thread(WatchConnecting);//将窗体线程设置为与后台同步threadWatch.IsBackground = true;//启动线程threadWatch.Start();//启动线程后 txtMsg文本框显示相应提示txtMsg.AppendText("开始监听客户端传来的信息!" + "\r\n");}}//创建一个负责和客户端通信的套接字 Socket socConnection = null;/// <summary>/// 监听客户端发来的请求/// </summary>private void WatchConnecting(){while (true) //持续不断监听客户端发来的请求{socConnection = socketWatch.Accept();txtMsg.AppendText("客户端连接成功" + "\r\n");//创建一个通信线程 ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);Thread thr = new Thread(pts);thr.IsBackground = true;//启动线程thr.Start(socConnection);}}/// <summary>/// 发送信息到客户端的方法/// </summary>/// <param name="sendMsg">发送的字符串信息</param>private void ServerSendMsg(string sendMsg){//将输入的字符串转换成 机器可以识别的字节数组byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendMsg);//向客户端发送字节数组信息socConnection.Send(arrSendMsg);//将发送的字符串信息附加到文本框txtMsg上txtMsg.AppendText("So-flash:" + GetCurrentTime() + "\r\n" + sendMsg + "\r\n");}/// <summary>/// 接收客户端发来的信息 /// </summary>/// <param name="socketClientPara">客户端套接字对象</param>private void ServerRecMsg(object socketClientPara){Socket socketServer = socketClientPara as Socket;while (true){//创建一个内存缓冲区 其大小为1024*1024字节 即1Mbyte[] arrServerRecMsg = new byte[1024 * 1024];//将接收到的信息存入到内存缓冲区,并返回其字节数组的长度int length = socketServer.Receive(arrServerRecMsg);//将机器接受到的字节数组转换为人可以读懂的字符串string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);//将发送的字符串信息附加到文本框txtMsg上 txtMsg.AppendText("天之涯:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n");}}private void BtnSendMsg_Click(object sender, EventArgs e){//调用 ServerSendMsg方法 发送信息到客户端ServerSendMsg(txtSendMsg.Text.Trim());}private void TxtSendMsg_KeyDown(object sender, KeyEventArgs e){//如果用户按下了Enter键if (e.KeyCode == Keys.Enter){//则调用 服务器向客户端发送信息的方法ServerSendMsg(txtSendMsg.Text.Trim());}}/// <summary>/// 获取当前系统时间的方法/// </summary>/// <returns>当前时间</returns>private DateTime GetCurrentTime(){DateTime currentTime = new DateTime();currentTime = DateTime.Now;return currentTime;}}
客户端代码:
public partial class Form1 : Form{public Form1(){InitializeComponent();//关闭对文本框的非法线程操作检查TextBox.CheckForIllegalCrossThreadCalls = false;}//创建 1个客户端套接字 和1个负责监听服务端请求的线程 Socket socketClient = null;Thread threadClient = null;private void BtnBeginListen_Click(object sender, EventArgs e){bool IsContain = false;int[] num = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };int i = 0;if (txtIP.Text.Contains(num[i].ToString())){//定义一个套字节监听 包含3个参数(IP4寻址协议,流式连接,TCP协议)socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//需要获取文本框中的IP地址IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim());//将获取的ip地址和端口号绑定到网络节点endpoint上IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPort.Text.Trim()));//这里客户端套接字连接到网络节点(服务端)用的方法是Connect 而不是BindsocketClient.Connect(endpoint);//创建一个线程 用于监听服务端发来的消息threadClient = new Thread(RecMsg);//将窗体线程设置为与后台同步threadClient.IsBackground = true;//启动线程threadClient.Start();}else{//定义一个套字节监听 包含3个参数(IP4寻址协议,流式连接,TCP协议)socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//需要获取文本框中的IP地址 IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());string ic = Convert.ToString(ips[1]);IPAddress ipaddress = IPAddress.Parse(ic);//将获取的ip地址和端口号绑定到网络节点endpoint上IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPort.Text.Trim()));//这里客户端套接字连接到网络节点(服务端)用的方法是Connect 而不是BindsocketClient.Connect(endpoint);//创建一个线程 用于监听服务端发来的消息threadClient = new Thread(RecMsg);//将窗体线程设置为与后台同步threadClient.IsBackground = true;//启动线程threadClient.Start();}}/// <summary>/// 接收服务端发来信息的方法/// </summary>private void RecMsg(){while (true) //持续监听服务端发来的消息{//定义一个1M的内存缓冲区 用于临时性存储接收到的信息byte[] arrRecMsg = new byte[1024 * 1024];//将客户端套接字接收到的数据存入内存缓冲区, 并获取其长度int length = socketClient.Receive(arrRecMsg);//将套接字获取到的字节数组转换为人可以看懂的字符串string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, 0, length);//将发送的信息追加到聊天内容文本框中txtMsg.AppendText("So-flash:" + GetCurrentTime() + "\r\n" + strRecMsg + "\r\n");}}/// <summary>/// 发送字符串信息到服务端的方法/// </summary>/// <param name="sendMsg">发送的字符串信息</param>private void ClientSendMsg(string sendMsg){//将输入的内容字符串转换为机器可以识别的字节数组byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);//调用客户端套接字发送字节数组socketClient.Send(arrClientSendMsg);//将发送的信息追加到聊天内容文本框中txtMsg.AppendText("天之涯:" + GetCurrentTime() + "\r\n" + sendMsg + "\r\n");}private void BtnSend_Click(object sender, EventArgs e){//调用ClientSendMsg方法 将文本框中输入的信息发送给服务端ClientSendMsg(txtCMsg.Text.Trim());}private void TxtCMsg_KeyDown(object sender, KeyEventArgs e){//当光标位于文本框时 如果用户按下了键盘上的Enter键 if (e.KeyCode == Keys.Enter){//则调用客户端向服务端发送信息的方法ClientSendMsg(txtCMsg.Text.Trim());}}/// <summary>/// 获取当前系统时间的方法/// </summary>/// <returns>当前时间</returns>private DateTime GetCurrentTime(){DateTime currentTime = new DateTime();currentTime = DateTime.Now;return currentTime;}}
将主机名转换为IP的核心代码:
IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());
上面的代码需要将IPAddress[]转化为IPAddress,以下的代码便可以实现
IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());string ic = Convert.ToString(ips[1]);IPAddress ipaddress = IPAddress.Parse(ic);//将IP地址和端口号绑定到网络节点endpoint上 IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //获取文本框上输入的端口号//监听绑定的网络节点