TCP中首先要在服务端开启监听,这样才可以从客户端链接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Collections;
using System.Net; namespace Server
{
class Program
{
static UdpClient server;
static ArrayList mblist;
//保存用户的
static Dictionary<string, IPEndPoint> dic = new Dictionary<string, IPEndPoint>();
static void AddMember(string nickNmae,IPEndPoint rep)//加入组
{
//mblist.Add(rep);
dic.Add(nickNmae,rep);
byte[] data = UDPComm.UDPComm.EncodingASCII(nickNmae+"已连接");
server.Send(data,data.Length,rep);
Console.WriteLine(nickNmae + "[" + rep.ToString() + "]" + "加入了组"); SendUserList();
//当用户更新后发送用户列表给所有用户
}
static void DelMember(IPEndPoint rep)//移除组
{
foreach (KeyValuePair<string, IPEndPoint> user in dic)
{
if (user.Value.Equals(rep))
{
byte[] data = UDPComm.UDPComm.EncodingASCII(user.Key + "退出了");
server.Send(data, data.Length, rep);
Console.WriteLine(user.Key + "[" + rep.ToString() + "]" + "退出了组");
dic.Remove(user.Key);
SendUserList();
break;//否则会报错,因为dic已经被修改
}
}
}
static void SendUserList()
{ string userlist = "UserList";
foreach (KeyValuePair<string, IPEndPoint> ss in dic)//取得所有用户
{
userlist += "|" + ss.Key;
} byte[] data = UDPComm.UDPComm.EncodingASCII(userlist);
foreach (KeyValuePair<string, IPEndPoint> ss in dic)//把用户表发给每个用户
{
server.Send(data, data.Length, ss.Value);
} }
static void SendToMember(IPEndPoint user,string message)//组类转发数据(第一个参数是谁发的,第二个是发的内容)
{
string name="";
foreach (KeyValuePair<string, IPEndPoint> ss in dic)//用来找出这个user的名字
{
if (ss.Value.Equals(user))//不能用"=="因为是两个不同的对象
{
name = ss.Key;//给要发送给各个客户端的信息加上发送人姓名;
//在服务端显示的信息
Console.WriteLine(name + "[" + user.ToString() + "]:" + message);
break;
}
}
foreach (KeyValuePair<string, IPEndPoint> d in dic)//循环给每个人都发送信息
{ byte[] data = UDPComm.UDPComm.EncodingASCII(name+" 说:"+message);
server.Send(data, data.Length, d.Value);
}
}
static void Main(string[] args)
{
IPAddress myIPAddress = (IPAddress)Dns.GetHostAddresses(Dns.GetHostName()).GetValue(2);
System.Console.Write(myIPAddress);
//string hostIP = "210.41.196.213";
string hostIP = myIPAddress.ToString();//
int port = 6666;
byte[] data;
string ReturnData;
IPEndPoint EndPoint;
IPAddress ipS = IPAddress.Parse(hostIP);//初始化本机
EndPoint = new IPEndPoint(ipS, port);
IPEndPoint test=null;//构造远程连接的参数
try
{
mblist = new ArrayList(); //server = new UdpClient(EndPoint);//创建本地连接的UdpClient实例
server = new UdpClient(6666);
Console.WriteLine("已启动,等待连接...");
while (true)
{
data = server.Receive(ref test);//接收数据,当Client端连接主机的时候,test就变成Cilent端的IP了 ReturnData = UDPComm.UDPComm.DecodingASCII(data); if (ReturnData.IndexOf("ADD") > -1)
{
string[] splitString = ReturnData.Split(',');//把从客户端发来的数据分开
string Command = splitString[0].Trim();
string name = splitString[1].ToLower();
AddMember(name,test); }
else if (ReturnData.IndexOf("DEL") > -1)
{
DelMember(test); }
else
{
if (dic.ContainsValue(test))//转发数据
{
SendToMember(test,ReturnData); }
}
}
}
catch (Exception e) { server.Close(); }
}
}
}

客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace Client
{
class Program
{
static string hostIP = "127.0.0.1";
static int port = 6666;
static UdpClient client;
byte[] data;
string sendData, ReturnData;
static IPEndPoint ipEnd;
IPEndPoint test = null;//用来在接收数据的时候对远程主机的信息存放
static void Main(string[] args)
{ IPAddress ipA = IPAddress.Parse(hostIP);//构造远程连接的参数
ipEnd = new IPEndPoint(ipA, port);
client = new UdpClient();// client = new UdpClient(ipEnd)这样的话就没有创建远程连接
client.Connect(ipEnd);//使用指定的远程主机信息建立默认远程主机连接 Thread threadReceive = new Thread(new ThreadStart(new Program().ReceiveData));
//threadReceive.IsBackground = true;
threadReceive.Start(); Thread threadSend = new Thread(new ThreadStart(new Program().SendData));
threadSend.Start();
}
public void SendData()
{
try
{
string first = string.Empty;
{
Console.WriteLine("请输入用户名");
sendData = "ADD," + Console.ReadLine().Trim();
data = UDPComm.UDPComm.EncodingASCII(sendData);//发送数据
client.Send(data, data.Length);
}
while (true)
{
sendData = Console.ReadLine();
if (sendData.IndexOf("DEL") > -1)
{
sendData = "DEL";
}
else if (sendData.IndexOf("QUIT") > -1)
{
data = UDPComm.UDPComm.EncodingASCII(sendData);//发送最后一次数据
client.Send(data, data.Length);
break;
} data = UDPComm.UDPComm.EncodingASCII(sendData);//发送数据
client.Send(data, data.Length); }
Console.WriteLine("退出");
client.Close(); }
catch (Exception e) { }
}
public void ReceiveData()
{
while (true)
{
data = client.Receive(ref test);//接收数据,
ReturnData = UDPComm.UDPComm.DecodingASCII(data);
Console.WriteLine(ReturnData);
}
}
}
}

上面就能够实现一个简单的聊天程序

最新文章

  1. Configure a VLAN (on top of a bond) with NetworkManager (nmcli) in RHEL7
  2. 细嗅Promise
  3. ctags and vim
  4. 20145334 第五次 java 实验报告
  5. CentOS7下安装JDK
  6. 302. Smallest Rectangle Enclosing Black Pixels
  7. Item47
  8. 具体解释HTML中的window对象和document对象
  9. if语句之猜拳
  10. 蜗牛—JSP学习乘法表页面输出
  11. Tickets 基础DP
  12. Python中的classmethod与staticmethod
  13. [Swift]LeetCode538. 把二叉搜索树转换为累加树 | Convert BST to Greater Tree
  14. typeHandler
  15. How to Read a Paper
  16. Python中logging日志模块的使用
  17. systemctl命令是系统服务管理器指令,它实际上将 service 和 chkconfig 这两个命令组合到一起。
  18. unity StrangeIoc
  19. Kali2.0通过xrdp实现windows远程链接Linux
  20. Android动画原理

热门文章

  1. CoreThink开发(十三)增加页面加载动画
  2. linux环境配置时钟同步ntpd服务
  3. go——接口(二)
  4. Eclipse 多行注释选择
  5. mybatis入门学习记录(一)
  6. linux mkisofs(genisoimage)命令用法
  7. Winform ObservableCollection 添加删除修改无效
  8. Silverlight应用小知识点
  9. 毕业一年后的java面试总结
  10. cisco笔记