• 服务端
    • 界面
    • Listener.cs
    • Sender.cs
    • Utils.cs
    • Form1.cs
    • AddMessageEventArgs.cs
  • 客户端
    • 界面
    • Sender.cs
    • Form1.cs
    • Utils.cs
  • 客户端可以看到其他在线用户
  • 客户端可以跟在线用户聊天
  • 服务端也可以跟在线用户聊天
服务端
界面

Listener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using WindowsFormsApplication4;
using System.Windows.Forms;
using UtilsNameSpace;namespace WindowsFormsApplication4
{class Listener{public static  TcpListener tclConnectListener;public static TcpListener tclMsgListener;public TcpClient tcpClient;public static int basePort = 9001;public BinaryReader br;public BinaryWriter bw;public string serverIp = "127.0.0.1";public event EventHandler<AddMessageEventArgs> onAddMessage;public event EventHandler<AddMessageEventArgs> onRemoveIp;public volatile bool listenerRun = true; // 开始监听public void start(){try{if (listenerRun == true){stop();//listenerRun = false;}}catch (Exception err){}finally{//IPAddress ip = getLocalIp();//IPEndPoint ipn = new IPEndPoint(ip, 8999);//tclConnectListener = new TcpListener(ipn);//tclConnectListener.Start();if(tclConnectListener == null &&tclMsgListener == null){startListenConnect();startListenMsg();}else{MessageBox.Show("不能重复启动");}}}// 信息监听public void startListenMsg(){try{Form1.form.tslStatusInfo.Text = "准备中";IPAddress ip = getLocalIp();IPEndPoint msgIpn = new IPEndPoint(ip, 9000); // 绑定本地监听通信端口tclMsgListener = new TcpListener(msgIpn);tclMsgListener.Start();Form1.form.tslStatusInfo.Text = "准备完毕";while (listenerRun){Socket socket = tclMsgListener.AcceptSocket();IPEndPoint remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;NetworkStream stream = new NetworkStream(socket);br = new BinaryReader(stream);// 数据结构// from;来自那里 e.g. 127.0.0.1:9001// to;送到哪里 e.g. 127.0.0.1"9002// msg;发送的信息string result = br.ReadString();Dictionary<string, string> dict = Utils.toDict(result);string from = Utils.getValueFormDict(dict, "from");string to = Utils.getValueFormDict(dict, "to");string msg = Utils.getValueFormDict(dict, "msg");string myEndPoint = Utils.getServerMsgEndpoint();// 如果信息是发给服务器的if (myEndPoint.Equals(to)){AddMessageEventArgs ame = new AddMessageEventArgs();ame.msg = new Dictionary<string, string>();ame.msg.Add("type", "2");ame.msg.Add("remote", from);ame.msg.Add("msg", msg);onAddMessage(this, ame);}else{Sender sender = new Sender(serverIp, from, to);sender.send(msg);//string toIp = Utils.getIpFromRemote(to);//int toPort = Utils.getPortFromRemote(to);//TcpClient tcl = new TcpClient(toIp, toPort);//NetworkStream ss = tcl.GetStream();//BinaryWriter bWriter = new BinaryWriter(ss);//bWriter.Write(result);//bWriter.Close();}//AddMessageEventArgs b = new AddMessageEventArgs();//b.msg = string.Format("{0};{1}", result, remote);//onAddMessage(this, b);}}catch (Exception err){Form1.form.tslStatusInfo.Text = "成功断开";}}// 监听连接public void startListenConnect(){try{IPAddress ip = getLocalIp();// 8999为监听连接的端口IPEndPoint ipn = new IPEndPoint(ip, 8999);tclConnectListener = new TcpListener(ipn);tclConnectListener.Start();listenerRun = true;Form1.form.tslStatusInfo.Text = "正在监听";string serverRemote = Utils.getRemote(serverIp.ToString(), 9000);AddMessageEventArgs serverAme = new AddMessageEventArgs();//ame.msg = string.Format("{0};{1};{2}", "成功连接", remote, "1");serverAme.msg = new Dictionary<string, string>();serverAme.msg.Add("type", "1");serverAme.msg.Add("remote", serverRemote);serverAme.msg.Add("msg", "成功启动");onAddMessage(this, serverAme);while (listenerRun){Form1.form.tslStatusInfo.Text = "准备就绪";Socket socket = tclConnectListener.AcceptSocket();NetworkStream stream = new NetworkStream(socket);br = new BinaryReader(stream);bw = new BinaryWriter(stream);string result = br.ReadString();// 数据结构// type; 连接类型 1:获取用户列表,0:连接相关// code; 操作类型 1:登陆 0:退出登陆// remote; 发出信息的远程客户机Dictionary<string, string> dict =  Utils.toDict(result);string type = Utils.getValueFormDict(dict, "type"); // if (type != null){if ("0".Equals(type)) // 连接请求{string code = Utils.getValueFormDict(dict, "code"); // 1:登陆,0:退出登陆if (code != null){if ("1".Equals(code.Trim())) // 登陆请求{bw.Write(Utils.generateLoginSuccessStruct(basePort, Form1.form.listConnect));// ip为设定的ip,端口是服务器分配的string remote = Utils.getRemote(ip.ToString(), basePort);// 供下一台主机使用basePort++;AddMessageEventArgs ame = new AddMessageEventArgs();//ame.msg = string.Format("{0};{1};{2}", "成功连接", remote, "1");ame.msg = new Dictionary<string, string>();ame.msg.Add("type", "1"); ame.msg.Add("remote", remote);ame.msg.Add("msg","成功连接");onAddMessage(this, ame);string response = Utils.gendrateOnlineClientStruct(Form1.form.listConnect);string sr = Utils.getRemote(serverIp, 9000);bw.Close();// 测试一下// 向每个在线用户更新在线用户列表foreach (string item in Form1.form.listConnect.Items){if (!remote.Equals(item) && !sr.Equals(item)){MessageBox.Show("合法用户:" + item);int port = Utils.getPortFromRemote(item);string ipa = Utils.getIpFromRemote(item);TcpClient tcl = new TcpClient(ipa, port);NetworkStream s = tcl.GetStream();BinaryWriter bWriter = new BinaryWriter(s);bWriter.Write(response);MessageBox.Show("写过去了");bWriter.Close();}}}else if ("0".Equals(code.Trim())) // 退出登陆{try{bw.Write("1");string remote = dict["remote"];Form1.form.chatIp = "";Form1.form.chatPort = -1;//string msg = String.Format("{0};{1}", "断开连接", remote);AddMessageEventArgs a = new AddMessageEventArgs();a.msg = new Dictionary<string, string>();a.msg.Add("type", "0");a.msg.Add("remote", remote);onRemoveIp(this, a);string response = Utils.gendrateOnlineClientStruct(Form1.form.listConnect);AddMessageEventArgs b = new AddMessageEventArgs();b.msg = new Dictionary<string, string>();b.msg.Add("type", "0");b.msg.Add("remote", remote);b.msg.Add("msg", "退出登陆");onAddMessage(this, b);//string response = Utils.gendrateOnlineClientStruct(Form1.form.listConnect);// 向每个在线用户更新在线用户列表foreach (string item in Form1.form.listConnect.Items){int port = Utils.getPortFromRemote(item);string ipa = Utils.getIpFromRemote(item);TcpClient tcl = new TcpClient(ipa, port);NetworkStream s = tcl.GetStream();BinaryWriter bWriter = new BinaryWriter(s);bWriter.Write(response);bWriter.Close();}}catch (Exception e){br.Close();bw.Close();socket.Dispose();socket.Close();}}}}else if ("1".Equals(type)) // 获取在线列表{}}else{MessageBox.Show("出错了");}//tcpClient.Close();}}catch (System.Security.SecurityException){bw.Write("0");br.Close();bw.Close();tcpClient.Close();MessageBox.Show("防火墙禁止");}catch (Exception e){Form1.form.tslStatusInfo.Text = "成功断开";}}// 向每个在线用户更新在线用户数public void updateOnlineClient(string remote){string response = Utils.gendrateOnlineClientStruct(Form1.form.listConnect);// 向每个在线用户更新在线用户列表foreach (string item in Form1.form.listConnect.Items){int port = Utils.getPortFromRemote(item);string ipa = Utils.getIpFromRemote(item);TcpClient tcl = new TcpClient(ipa, port);NetworkStream s = tcl.GetStream();BinaryWriter bWriter = new BinaryWriter(s);bWriter.Write(response);bWriter.Close();}}// 停止监听public void stop(){try{listenerRun = false;if (tcpClient != null){tcpClient.Close();}if (br != null){br.Close();}if (bw != null){bw.Close();}if (tclConnectListener != null){tclConnectListener.Stop();}if (tclMsgListener != null){tclMsgListener.Stop();}}catch (Exception e){MessageBox.Show("出错了:"+e.Message);}}// 获取本机oppublic IPAddress getLocalIp(){//IPAddress ip = Dns.GetHostByName(Dns.GetHostName()).AddressList[0];return IPAddress.Parse("127.0.0.1");} 监听句柄:监听信息添加//public void onAddMessage()//{//} 监听句柄:监听ip移除//public void onRemveIp()//{//}}
}
Sender.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using UtilsNameSpace;namespace WindowsFormsApplication4
{class Sender{public string serverIp;public int serverPort = 9000; // 9000是监听信息传送的端口public string from;public string to;public string ip;public int port;public TcpClient tcpClient;public BinaryReader br;public BinaryWriter bw;public Sender(string serverIp, string from, string to){this.serverIp = serverIp;this.from = from;this.to = to;}public void send(string msg){//try//{string toIp = Utils.getIpFromRemote(to);int toPort = Utils.getPortFromRemote(to);tcpClient = new TcpClient(toIp, toPort);NetworkStream stream = tcpClient.GetStream();bw = new BinaryWriter(stream);string r = Utils.generateInfoSendStruct(from, to, msg);MessageBox.Show("信息结构为:" + r);bw.Write(r);bw.Close();//}//catch (exception e)//{//    if (tcpclient != null)//    {//        tcpclient.close();//    }//    if(bw != null)//    {//        bw.close();//    }//    messagebox.show("出错了:" + e.message);//}}}
}
Utils.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace UtilsNameSpace
{class Utils{// json转字典public static Dictionary<string, string> toDict(string s){Dictionary<string, string> dict = new Dictionary<string, string>();string[] list = s.Trim().Split('{', ';', '}');foreach (string item in list){if (!"".Equals(item)){string[] obj = item.Split('|');dict.Add(obj[0].Trim(), obj[1].Trim());}}return dict;}// 从字典中获取值public static string getValueFormDict(Dictionary<string, string> dict, string name){try{return dict[name].Trim();}catch (Exception e){return null;}}// 组合成remote形式 e.g. 127.0.0.1:8999public static string getRemote(string ip, int port){return String.Format("{0}:{1}", ip, port);}// 从remote中获取端口public static int getPortFromRemote(string remote){return int.Parse(remote.Split(':')[1]);}// 从remote中获取ippublic static string getIpFromRemote(string remote){return remote.Split(':')[0].ToString();}// 生成信息public static string generateInfo(string remote, string msg){return remote + ">:" + System.DateTime.Now.ToString() + Environment.NewLine + msg + Environment.NewLine;}// 生成成功登陆返回信息public static string generateLoginSuccessStruct(int port, ListBox listBox){string s = "{type|0;port|" + port + ";remotes|";int len = listBox.Items.Count;if (len > 0){for (int i = 0; i < len - 1; i++){s += listBox.Items[i] + ",";}s += listBox.Items[len - 1] + "}";}else{s += "}";}return s;}// 生成更新在线用户信息结构public static string gendrateOnlineClientStruct(ListBox listBox){string s = "{type|1;" + "remotes|";int len = listBox.Items.Count;if (len > 0){for (int i = 0; i < len - 1; i++){s += listBox.Items[i] + ",";}s += listBox.Items[len - 1] + "}";}else{s += "}";}return s;}public static string getServerMsgEndpoint(){return "127.0.0.1:9000";}// 生成发送信息的结构public static string generateInfoSendStruct(string from, string to, string msg){//string r = String.Format("{from|{0};to|{1};msg|{2}", from, to, msg);string r = "{from|" + from + ";" + "to|" + to + ";" + "msg|" + msg + "}";return r;}}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using WindowsFormsApplication4;
using UtilsNameSpace;namespace WindowsFormsApplication4
{public partial class Form1 : Form{Listener listener;public delegate void AddClient(string remote);public AddClient addClient;public delegate void RemoveClient(string remote);public RemoveClient removeClient;public delegate void AppenText(string appendText);public AppenText appendText;public string chatIp;public int chatPort;public string serverIp = "127.0.0.1";public int serverMsgPort = 9000;public static Form1 form;public Form1(){InitializeComponent();CheckForIllegalCrossThreadCalls = false;form = this;addClient = new AddClient(addClientIp);removeClient = new RemoveClient(removeClientIp);appendText = new AppenText(appendTextToRich);}// 启动监听按钮private void tslStartListen_Click(object sender, EventArgs e){startListen();}// 停止监听按钮private void tslStopListen_Click(object sender, EventArgs e){try{setStatusInfo("正在停止");if (listener != null){listener.stop();}setStatusInfo("已经停止");}catch (Exception err){MessageBox.Show("出错了:" + err.Message);}}// 启动监听private void startListen(){listener = new Listener();listener.onAddMessage += new EventHandler<AddMessageEventArgs>(this.addMessage);listener.onRemoveIp += new EventHandler<AddMessageEventArgs>(this.remoteIp);// 连接监听Thread t1 = new Thread(new ThreadStart(listener.startListenConnect));t1.IsBackground = true;t1.Start();// 信息发送监听Thread t2 = new Thread(new ThreadStart(listener.startListenMsg));t2.IsBackground = true;t2.Start();}// 聊天窗口添加信息// tip: 头部提示信息// msg: 信息内容public void appendTextToRich(string msg){//int textLen = list[0].Length;//int typeTipLen = list[1].Length;rtbChatContent.AppendText(msg);//rtbChatContent.Select(0, textLen-list[0].Length - Environment.NewLine.Length * 2 - typeTipLen);//rtbChatContent.SelectionColor = Color.Red;rtbChatContent.ScrollToCaret();}// 添加显示信息void addMessage(object sender, AddMessageEventArgs e){//string text = e.msg;Dictionary<string, string> dict = e.msg;string remote = dict["remote"];//string[] clientList = remote.Split(':');string ip = Utils.getIpFromRemote(remote);int port = Utils.getPortFromRemote(remote);string type = dict["type"];// 是登陆登陆if ("1".Equals(type.Trim())){if (!listConnect.Items.Contains(ip)) // 不存在就添加{listConnect.Invoke(addClient, remote);}}string msg = dict["msg"];// 添加当前用户为聊天对象chatIp = ip;chatPort = port;string info = Utils.generateInfo(remote, msg);rtbChatContent.Invoke(appendText, info);}// 添加客户端列表public void addClientIp(string remote){listConnect.Items.Add(remote);}// 取出客户端里诶博爱public void removeClientIp(string remote){listConnect.Items.Remove(remote);}// 客户端退出void remoteIp(object sender, AddMessageEventArgs e){string remote = e.msg["remote"];listConnect.Invoke(removeClient, remote);}// 显示本机ippublic void setLocalIp(string remote){lblMyIp.Text = remote;}// 设置状态public void setStatusInfo(string info){tslStatusInfo.Text = info;}private void btnSend_Click(object sender, EventArgs e){MessageBox.Show("正在聊天的是" + chatIp+":"+chatPort);if (chatIp == null || "".Equals(chatIp.Trim()) || chatPort == null || chatPort < 0){MessageBox.Show("请选择一个聊天的对象");return;}setStatusInfo("发送中");try{string msg = rtbInput.Text;if (msg == null || "".Equals(msg)){MessageBox.Show("发送的信息不能为空");return;}if (chatIp == null || "".Equals(chatIp)){MessageBox.Show("连接出错");return;}string from = Utils.getRemote(serverIp, 9000);string to = Utils.getRemote(chatIp, chatPort);Sender s = new Sender(serverIp, from, to);s.send(msg);resetRichText();setStatusInfo("发送成功");}catch (Exception err){MessageBox.Show("出错了:" + err.Message);}}// 重置文本public void resetRichText(){rtbInput.Text = "";}private void Form1_Load(object sender, EventArgs e){}private void listConnect_SelectedIndexChanged(object sender, EventArgs e){}private void listConnect_DoubleClick(object sender, EventArgs e){MouseEventArgs me = (MouseEventArgs)e;if (me.Clicks != 0){if (listConnect.SelectedItem != null){string remote = listConnect.SelectedItem.ToString();chatIp = Utils.getIpFromRemote(remote);chatPort = Utils.getPortFromRemote(remote);}}}}
}
AddMessageEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace WindowsFormsApplication4
{class AddMessageEventArgs:EventArgs{// type: 信息类型; 0:退出登陆 , 1:登陆,2:传递消息// remote:发出信息的远程客户机;e.g. 127.0.0.1:8999// msg:提示的信息// from:消息来源 e.g. 127.0.0.1:9001// to:消息去向 e.g. 127.0.0.1:9002public Dictionary<string, string> msg ;}
}
客户端
界面

Sender.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using UtilsNameSpace;namespace WindowsFormsApplication4
{class Sender{public string serverIp;public int serverPort = 9000; // 9000是监听信息传送的端口public string from;public string to;public string ip;public int port;public TcpClient tcpClient;public BinaryReader br;public BinaryWriter bw;public Sender(string serverIp, string from, string to){this.serverIp = serverIp;this.from = from;this.to = to;}public void send(string msg){//try//{tcpClient = new TcpClient(serverIp, serverPort);NetworkStream stream = tcpClient.GetStream();bw = new BinaryWriter(stream);string r = Utils.generateInfoSendStruct(from, to, msg);MessageBox.Show("信息结构为:" + r);bw.Write(r);bw.Close();//}//catch (Exception e)//{//    if (tcpClient != null)//    {//        tcpClient.Close();//    }//    if(bw != null)//    {//        bw.Close();//    }//    MessageBox.Show("出错了:" + e.Message);//}}}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using WindowsFormsApplication4;
using System.IO;
using UtilsNameSpace;namespace WindowsFormsApplication4
{public partial class Form1 : Form{public static int myport; // 我的端口TcpListener tclListener;Socket socket;public BinaryWriter bw;public BinaryReader br;public string chatTo;public static string serverIp;public static int serverConnectPort = 8999;public static int serverMsgPort = 9000;public static string chatIp ;public int chatPort = 9000;public bool listenerRun = true;public static string myIp = "127.0.0.1";public delegate void AppenText(string appendText);public AppenText appendText;public delegate void AppendClientsToList(string remotes);public AppendClientsToList appendClientsToList;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){appendText = new AppenText(appendTextToRich);appendClientsToList = new AppendClientsToList(addRemotesToListConnect);//Thread t = new Thread(new ThreadStart(startListen));//t.Start();}// 添加信息到对话框public void appendTextToRich(string tl){string[] list = tl.Split(';');int textLen = list[0].Length;int typeTipLen = list[1].Length;rtbChatContent.AppendText(list[0]);rtbChatContent.Select(0, textLen - list[0].Length - Environment.NewLine.Length * 2 - typeTipLen);rtbChatContent.SelectionColor = Color.Red;rtbChatContent.ScrollToCaret();}// 添加显示信息void addMessage(string remote, string typeTip){string[] list = remote.Split(':');string ip = list[0];string port = list[1];string t = remote + ">:" + System.DateTime.Now.ToString() + Environment.NewLine + typeTip + Environment.NewLine;string tl = t + ";" + typeTip;rtbChatContent.Invoke(appendText, tl);}// 启动监听public void startListen(){try{setStatusInfo("准备中");IPAddress ip = getLocalIp();IPEndPoint ipn = new IPEndPoint(ip, myport);tclListener = new TcpListener(ipn);tclListener.Start();setStatusInfo("准备完毕");while (listenerRun){socket = tclListener.AcceptSocket();NetworkStream stream = new NetworkStream(socket);br = new BinaryReader(stream);string result = br.ReadString();MessageBox.Show("监听中的信息:"+result);Dictionary<string, string> dict = Utils.toDict(result);string type = Utils.getValueFormDict(dict, "type");string from = Utils.getValueFormDict(dict, "from");string msg = Utils.getValueFormDict(dict, "msg");//MessageBox.Show();if (from != null && toolStrip1 != null){addMessage(from, msg);}MessageBox.Show("type:" + type);if ("1".Equals(type)) // 在线用户列表更新{MessageBox.Show("更新请求:"+dict["remotes"]);listConnect.Invoke(appendClientsToList, dict["remotes"]);}}}catch (Exception err){setStatusInfo("成功断开");}}public IPAddress getLocalIp(){return IPAddress.Parse(myIp);}// 连接点击事件private void btnConnect_Click(object sender, EventArgs e){Thread t = new Thread(new ThreadStart(startConnect));t.Start();}// 开始连接public void startConnect(){TcpClient tcpClient = null;try{serverIp = txtServerIp.Text.Trim();chatIp = serverIp;if (serverIp == null || "".Equals(serverIp)){MessageBox.Show("请输入合法的IP");return;}setStatusInfo("正在连接");tcpClient = new TcpClient();tcpClient.Connect(serverIp, serverConnectPort);NetworkStream stream = tcpClient.GetStream();bw = new BinaryWriter(stream);br = new BinaryReader(stream);bw.Write(Utils.genderateLoginStruct());string result = br.ReadString();MessageBox.Show("服务端返回信息:" + result);// type; 信息类型   0:是一个连接相关的回复  1:是一个更新在线用户列表的请求// port; 生成的端口// remotes;在线用户列表Dictionary<string, string> dict = Utils.parseLoginResponseStruct(result);string type = dict["type"].ToString();string port = dict["port"].ToString();// 连接回复if ("0".Equals(type)){if (!"-1".Equals(port.Trim())){setStatusInfo("连接成功");myport = int.Parse(port);Thread t = new Thread(new ThreadStart(startListen));t.Start();listConnect.Invoke(appendClientsToList, dict["remotes"]);addMessage(Utils.getRemote(serverIp, serverMsgPort), "成功连接");}else{setStatusInfo("连接失败");}}bw.Close();br.Close();tcpClient.Close();}catch (Exception e){if (bw != null){bw.Close();}if (br != null){br.Close();}if (tcpClient != null){tcpClient.Close();}MessageBox.Show("连接失败:" + e.Message);setStatusInfo("连接失败");}}// 添加信息到已连接列表上public void addRemotesToListConnect(string remotes){string[] rs = Utils.parseRemotes(remotes);string myremote = Utils.getRemote(myIp, myport);listConnect.Items.Clear();foreach (string remote in rs){// 不包含自己if (!myremote.Equals(remote)&&!"".Equals(remote.Trim())){listConnect.Items.Add(remote);}}}// 设置状态信息public void setStatusInfo(string status){tslStatusInfo.Text = status;}private void btnDisConnect_Click(object sender, EventArgs e){TcpClient tcpClient = new TcpClient();tcpClient.Connect(serverIp, serverConnectPort);NetworkStream stream = tcpClient.GetStream();bw = new BinaryWriter(stream);br = new BinaryReader(stream);bw.Write(Utils.genderateLogoutStruct(Utils.getRemote(myIp, myport)));string status = br.ReadString();if ("1".Equals(status.Trim())){listConnect.Items.Clear();setStatusInfo("成功断开");addMessage(String.Format("{0}:{1}", serverIp, serverConnectPort), "成功断开");listenerRun = false;tclListener.Stop();}else{setStatusInfo("异常");}bw.Close();br.Close();tcpClient.Close();}// 重置文本public void resetRichText(){rtbInput.Text = "";}private void btnSend_Click(object sender, EventArgs e){MessageBox.Show("正在聊天的是" + chatIp + ":" + chatPort);if (chatIp == null || "".Equals(chatIp.Trim()) || chatPort == null || chatPort < 0){MessageBox.Show("请选择一个聊天的对象");return;}//try//{setStatusInfo("发送中");string msg = rtbInput.Text;if (msg == null || "".Equals(msg)){MessageBox.Show("发送的信息不能为空");return;}if (serverIp == null || "".Equals(serverIp)){MessageBox.Show("连接出错");return;}string from = Utils.getRemote(myIp, myport);string to = Utils.getRemote(chatIp, chatPort);Sender s = new Sender(serverIp, from, to);s.send(msg);resetRichText();setStatusInfo("发送成功");//}//catch (Exception err)//{//    MessageBox.Show("出错了:" + err.Message);//}}private void listConnect_DoubleClick(object sender, EventArgs e){MouseEventArgs me = (MouseEventArgs)e;if (me.Clicks != 0){if (listConnect.SelectedItem != null){string remote = listConnect.SelectedItem.ToString();chatIp = Utils.getIpFromRemote(remote);chatPort = Utils.getPortFromRemote(remote);}}}}
}
Utils.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace UtilsNameSpace
{class Utils{// 生成登陆数据结构// type; 0:表示是连接相关请求// code;1:登陆,0:退出登陆public static string genderateLoginStruct(){return "{type|0;code|1}";}// 生成退出数据结构// type; 0:表示是连接相关请求// code;1:登陆,0:退出登陆public static string genderateLogoutStruct(string remote){return "{type|0;code|0;remote|" + remote + "}";}// json转字典public static Dictionary<string, string> toDict(string s){Dictionary<string, string> dict = new Dictionary<string, string>();string[] list = s.Trim().Split('{', ';', '}');foreach (string item in list){if (!"".Equals(item)){string[] obj = item.Split('|');dict.Add(obj[0].Trim(), obj[1].Trim());}}return dict;}// 解析已连接客户端的数据结构public static string[] parseRemotes(string remotes){string[] result = remotes.Split(',');return result;}// 组合成remote形式 e.g. 127.0.0.1:8999public static string getRemote(string ip, int port){return String.Format("{0}:{1}", ip, port);}// 从remote中获取端口public static int getPortFromRemote(string remote){return int.Parse(remote.Split(':')[1]);}// 从remote中获取ippublic static string getIpFromRemote(string remote){return remote.Split(':')[0].ToString();}// 解析登陆回复结构// port:分配的端口// remotes:登陆的远端的组合 e.g. 127.0.0.1:9001,127.0.0.1:9002public static Dictionary<string, string> parseLoginResponseStruct(string json){Dictionary<string, string> dict = toDict(json);//Dictionary<string, object> result = new Dictionary<string, object>();//result.Add("port", dict["port"]);//result.Add("remotes", parseRemotes(dict["remotes"]));return dict;}// 从字典中获取值public static string getValueFormDict(Dictionary<string, string> dict, string name){try{return dict[name].Trim();}catch (Exception e){return null;}}// 生成发送信息的结构public static string generateInfoSendStruct(string from, string to, string msg){//string r = String.Format("{from|{0};to|{1};msg|{2}", from, to, msg);string r = "{from|" + from + ";" + "to|" + to + ";" + "msg|" + msg + "}";return r;}}
}

C#网络编程(五)----基于TCP的简易多客户端聊天相关推荐

  1. TCP/IP网络编程之基于TCP的服务端/客户端(一)

    TCP/IP网络编程之基于TCP的服务端/客户端(一) 理解TCP和UDP 根据数据传输方式的不同,基于网络协议的套接字一般分为TCP套接字和UDP套接字.因为TCP套接字是面向连接的,因此又称为基于 ...

  2. TCP/IP网络编程之基于TCP的服务端/客户端(二)

    回声客户端问题 上一章TCP/IP网络编程之基于TCP的服务端/客户端(一)中,我们解释了回声客户端所存在的问题,那么单单是客户端的问题,服务端没有任何问题?是的,服务端没有问题,现在先让我们回顾下服 ...

  3. 【网络编程】基于TCP/IP协议的C/S模型

    相关视频--C3程序猿-windows网络编程:第一部分tcp/ip 我的小站--半生瓜のblog 基于TCP/IP协议的C/S模型 基于TCP/IP协议的C/S模型 TCP/IP协议 Client/ ...

  4. 【python网络编程】创建TCP/UDP服务器进行客户端/服务器间通信

    客户端/服务器网络编程介绍 套接字:通信端点 实例:客户端发送数据,接收服务器返回的时间戳 用Python 编写FTP 客户端程序 客户端/服务器网络编程介绍 软件服务器也运行在一块硬件之上,但是没有 ...

  5. Python核心编程(第3版)第2章网络编程中关于tcp/udp服务器和客户端实现代码的运行出错的修正

    在Python核心编程(第3版)第2章网络编程中, 关于tcp/udp服务器和客户端实现代码的运行会出现 ['str' does not support the buffer interface]之类 ...

  6. Qt网络程序:基于TCP的服务器、客户端实例

    首先我们需要设置服务器:  项目文件中加入:QT += network  相关头文件: #include<QTcpServer>//监听套接字 #include<QTcpSocket ...

  7. 【Socket网络编程】4.tcp和udp的客户端和服务端收发流程

    tcp和udp的客户端和服务端收发流程 1.udp服务器流程: 1.创建serverSocket 2.设置服务器地址 serverAddr 3.将serverSocket和serverAddr绑定 b ...

  8. Python之网络编程(基于tcp实现远程执行命令)

    文章目录 实现目标 服务端分析 客户端分析 远程执行结果 本篇是用tcp套接字实现的一个远程执行命令的小案例,tcp套接字是一种面向连接的Socekt,针对面向连接的TCP服务应用,安全,但是效率低 ...

  9. 【Linux网络编程】基于TCP流 I/O多路转接(poll) 的高性能http服务器

    服务器比较简陋,为了学习poll的使用,只向客户端回写一条html语句.启动服务器后,浏览器发起请求,服务端向浏览器写回html,响应字符串,然后可以看到,浏览器解析并显示 Hello Poll!. ...

  10. Linux下基于TCP的简易文件传输(socket编程)

    Linux下基于TCP的简易文件传输(socket编程) OSI和TCP/IP: 关于TCP/IP协议 关于TCP协议 TCP编程的一般步骤[^2] TCP文件传输实现 功能概述 服务器编程 客户端编 ...

最新文章

  1. 显卡显存故障检测工具_【硬件资讯】1660super实锤!更换DDR6显存!带宽超1660ti!...
  2. 汉字内码UNICODE转换表
  3. 云原生生态周报 Vol. 14 | K8s CVE 修复指南
  4. Tomcat 7 自动加载类及检测文件变动原理
  5. 学习笔记之-Activiti7工作流引擎,概述,环境搭建,类关系图,使用Activiti BPMN visualizer,流程变量,组任务 网关,Activiti整合Spring SpringBoot
  6. web前端开发职业技能证书_1+x证书web前端开发职业技能等级标准1
  7. 每日一言学做人,古之学问,博大精深
  8. 智商情商哪个重要_《所谓逆商高,就是心态好》:逆商,比情商和智商更重要...
  9. hadoop rpc客户端初始化和调用过程详解
  10. linux下 mysql主从备份
  11. 华三ap设置无线服务器,H3C无线控制器实现Remote AP功能典型配置举例(V7)
  12. Java Map 接口
  13. 微服务框架自带uuid生成器
  14. Ubuntu录制gif动态图
  15. 【python逻辑算法题】一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法
  16. SylixOS这个操作系统怎么样?
  17. ipsec-***过程
  18. 设平衡二叉排序树(AVL树) 的节点个数为n,则其平均检索长度为log2n
  19. wndDL课程学习笔记
  20. windows无法完成更新正在撤销更改

热门文章

  1. MySQL执行多表联查时,报错ln aggregated query without GROUP BY
  2. 读书笔记之怎样在股市获得稳健收益
  3. 耳机四根线的图解_耳机五根线如何连接
  4. html中button标签reset用法
  5. 安卓自动化实战项目(AutoJs)-抖音自动取关脚本
  6. 用计算机实测技术研究声波和拍内容,大学物理实验
  7. zigbee模块和433无线模块的区别
  8. 「ZigBee模块」基础实验(4)定时器T1的简单应用
  9. prosody xmpp_如何在Ubuntu 18.04上安装Prosody
  10. 如何通过vin及发动机号查询车辆出险、理赔、事故记录