关于C#socket通信,分为同步和异步通信,本文简单介绍一下同步通信。
通信两端分别为客户端(Client)和服务器(Server):
(1)Cient:(客户端)
1:建立一个Socket对像;
2:用socket对像的Connect()方法以上面建立的EndPoint对像做为参数,向服务器发出连接请求;
3:如果连接成功,就用socket对像的Send()方法向服务器发送信息;
4:用socket对像的Receive()方法接受服务器发来的信息 ;
5:通信结束后一定记得关闭socket (未实现);
代码有待完善,只是简单的介绍客户端的创建。(会产生粘包等问题)
仅供参考仅供参考
class Client
{
Socket tcpClient;
public Client(string ip,int port) {
//创建Socket
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//地址
IPAddress iPAddress;
if (!IPAddress.TryParse(ip,out iPAddress)) {
Console.WriteLine("IP地址有误,创建客户端失败");
return;
}
//地址:端口号
IPEndPoint point = new IPEndPoint(iPAddress,port);
try
{
tcpClient.Connect(point);//通过ip:端口号来定位一个要连接服务器
}
catch (Exception e) {
Console.WriteLine(e.Message);//如果访问的服务器未打开 抛出异常信息
return;
}
Console.WriteLine("连接成功");
}
public void Start() {
Thread th = new Thread(SendMessage);
th.Start();
th.IsBackground = true;
this.ReceiveMessage();
}
/// <summary>
/// 客户端发送信息
/// </summary>
public void SendMessage() {
while (true) {
string value = Console.ReadLine();
byte[] data = Encoding.Default.GetBytes(value);
tcpClient.Send(data);
}
}
/// <summary>
/// 客服端接收信息
/// </summary>
public void ReceiveMessage() {
try
{
while (true)
{
byte[] arr = new byte[100 * 1024]; ;//arr用来接收数据 (相当于一个篮子)
int num = tcpClient.Receive(arr);
string data = Encoding.Default.GetString(arr, 0, num);//只把接收到的数据进行转换
Console.WriteLine(data);
}
}
catch (Exception e) {
Console.WriteLine("服务器已断开");
}
}
}
(2)Server:(服务器)
1:建立一个Socket对像;
2:用socket对像的Bind()方法绑定EndPoint;
3:用socket对像的Listen()方法开始监听;
4:接受到客户端的连接,用socket对像的Accept()方法创建新的socket对像用于和请求的客户端进行通信;
5:用新的socket对象接收(Receive)和发送(Send)消息。
代码有待完善,只是简单的介绍服务器的创建。
仅供参考仅供参考
class Server
{
Socket tcpServer;
List<Socket> users = new List<Socket>();//创建客户端列表
public Server(string ip, int port)
{
//1.创建socket
tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.绑定IP地址和端口号
IPAddress ipAddress;
if (!IPAddress.TryParse(ip, out ipAddress))
{
Console.WriteLine("IP地址有误,创建服务器失败");
return;
}
IPEndPoint point = new IPEndPoint(ipAddress, port);
tcpServer.Bind(point);
//限制只能100个用户接入,如果参数为0则无限制
tcpServer.Listen(100);
}
public void Start()
{
Thread th = new Thread(UserAccept);
th.Start();
Thread th1 = new Thread(SendToAll);
th1.Start();
//Thread th2 = new Thread(ReceiveMessage);
//th2.Start();
}
/// <summary>
/// 接收用户的连接
/// </summary>
public void UserAccept()
{
Console.WriteLine("等待用户连接...");
while (true)
{
Socket user = tcpServer.Accept();
//this.ReceiveAsync(user);
Thread thread = new Thread(ReceiveMessage);
thread.Start(user);//每加进来一个客户端增加一个线程
IPEndPoint str = user.RemoteEndPoint as IPEndPoint;
Console.WriteLine(str.Address + "已连接");
users.Add(user);
}
}
/// <summary>
/// 服务器发送信息
/// </summary>
public void SendToAll()
{
while (true)
{
string value = Console.ReadLine();
byte[] data = Encoding.Default.GetBytes(value);
for (var i = 0; i < users.Count; i++)
{
try
{
users[i].Send(data);//For循环发送给每个客户端
}
catch (SocketException e)
{
IPEndPoint str = users[i].RemoteEndPoint as IPEndPoint;
Console.WriteLine(str.Address + "已断开连接");
users.RemoveAt(i);//抛出该异常说明该客户已断开连接 将其移除
i--;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
/// <summary>
/// 服务器接收信息
/// </summary>
public void ReceiveMessage(object user)
{
Socket client = user as Socket;
while (true)
{
byte[] arr = new byte[100 * 1024];
try
{
int num = client.Receive(arr);
string value = Encoding.Default.GetString(arr, 0, num);
IPEndPoint str = client.RemoteEndPoint as IPEndPoint;
value = str.Address + ":" + value;//把客户端的地址打印出来
Console.WriteLine(value);
SendToAll(value, client);//把客户端发过来的消息群发出去
}
catch (SocketException e)
{
IPEndPoint str = client.RemoteEndPoint as IPEndPoint;
Console.WriteLine(str.Address + "已下线");
users.Remove(client);
Thread.CurrentThread.Abort();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// 转发消息给其他所有客户端
/// </summary>
/// <param name="str">消息</param>
/// <param name="user">发消息的客户端</param>
public void SendToAll(string str, object user)
{
Socket client = user as Socket;
byte[] data = Encoding.Default.GetBytes(str);
for (var i = 0; i < users.Count; i++)
{
try
{
if (client != users[i])
{
users[i].Send(data);
}
}
catch (SocketException e)
{
IPEndPoint str1 = users[i].RemoteEndPoint as IPEndPoint;
Console.WriteLine(str1.Address + "已下线");
users.RemoveAt(i);
i--;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
4507



被折叠的 条评论
为什么被折叠?



