码迷,mamicode.com
首页 > Windows程序 > 详细

C#的Socket通信Demo

时间:2020-10-13 17:36:49      阅读:35      评论:0      收藏:0      [点我收藏+]

标签:开启   itop   space   包含   ddr   indexof   字节数组   console   client   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketDemo
{
class Program
{
static void Main(string[] args)
{
Connect();
}

#region Client
//创建1个客户端套接字和1个负责监听服务端请求的线程
static Thread ThreadClient = null;
static Socket SocketClient = null;
private static void Connect()
{
try
{
//string host = "192.168.0.2";//服务器端ip地址
string host = "127.0.0.1";//服务器端ip地址
int port = 12580;//60.171.108.154 //60.171.108.192
//Console.WriteLine("请输入IP地址:");
//string host = Console.ReadLine();//服务器端ip地址

//Console.WriteLine("请输入端口号:");
//int port = int.Parse(Console.ReadLine());

IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);

//定义一个套接字监听
SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

try
{
//客户端套接字连接到网络节点上,用的是Connect
SocketClient.Connect(ipe);
}
catch (Exception)
{
Console.WriteLine("连接失败!\r\n");
Console.ReadLine();
return;
}

ThreadClient = new Thread(Recv);
ThreadClient.IsBackground = true;
ThreadClient.Start();

Thread.Sleep(1000);
Console.WriteLine("请输入内容<按Enter键发送>:\r\n");
while (true)
{
string sendStr = Console.ReadLine();
//string sendStr = "3";
ClientSendMsg(sendStr);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}

}

//static string strTemps = "";
/// <summary>
/// 接收服务端发来信息的方法
/// </summary>
private static void Recv()
{
int x = 0;
//持续监听服务端发来的消息
while (true)
{
try
{
//定义一个1M的内存缓冲区,用于临时性存储接收到的消息
byte[] arrRecvmsg = new byte[1024 * 1024];

//将客户端套接字接收到的数据存入内存缓冲区,并获取长度
int length = SocketClient.Receive(arrRecvmsg);

//将套接字获取到的字符数组转换为人可以看懂的字符串
string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);

if (x == 1)
{
Console.WriteLine("\r\n服务器:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "\r\n" + strRevMsg + "\r\n");

}
else
{
Console.WriteLine(strRevMsg + "\r\n");
x = 1;
}
//strTemps += strRevMsg;
//string[] strRevMsgs = strTemps.Split(new char[] { ‘,‘ }, StringSplitOptions.RemoveEmptyEntries);
//int.TryParse(strRevMsgs[0], out length);

//if (length == (strTemps.Length - (strTemps.IndexOf(‘,‘) + 1)))
//{
// log.DebugFormat($"1ImageBase64Length:{strTemps.Length}|ImageBase64:{strTemps}");
// strTemps = strTemps.Substring((strTemps.IndexOf(‘,‘) + 1));
// log.DebugFormat($"2ImageBase64Length:{strTemps.Length}|ImageBase64:{strTemps}");
// VisitorManagement visitorManagement = new VisitorManagement();
// string code = visitorManagement.VisitorManagements();
// if (code != "0000")
// ClientSendMsg(code);
//}
}
catch (Exception ex)
{
Console.WriteLine("远程服务器已经中断连接!" + ex.Message + "\r\n");
//log.DebugFormat("远程服务器已经中断连接!" + ex.ToString());
break;
}
}

}
/// <summary>
/// 发送字符信息到服务端的方法
/// </summary>
/// <param name="sendMsg"></param>
private static void ClientSendMsg(string sendMsg)
{
//将输入的内容字符串转换为机器可以识别的字节数组
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
//调用客户端套接字发送字节数组
SocketClient.Send(arrClientSendMsg);

}
#endregion

#region 服务器
//创建一个和客户端通信的套接字
static Socket SocketWatch = null;
//定义一个集合,存储客户端信息
static Dictionary<string, Socket> ClientConnectionItems = new Dictionary<string, Socket> { };
public void Server()
{
//端口号(用来监听的)
int port = 12580;

//string host = "127.0.0.1";
//IPAddress ip = IPAddress.Parse(host);
IPAddress ip = IPAddress.Any;

//将IP地址和端口号绑定到网络节点point上
IPEndPoint ipe = new IPEndPoint(ip, port);

//定义一个套接字用于监听客户端发来的消息,包含三个参数(IP4寻址协议,流式连接,Tcp协议)
SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//监听绑定的网络节点
SocketWatch.Bind(ipe);
//将套接字的监听队列长度限制为20
SocketWatch.Listen(20);


//负责监听客户端的线程:创建一个监听线程
Thread threadwatch = new Thread(WatchConnecting);
//将窗体线程设置为与后台同步,随着主线程结束而结束
threadwatch.IsBackground = true;
//启动线程
threadwatch.Start();
Console.WriteLine("开启监听......");
Console.WriteLine("点击输入任意数据回车退出程序......");
Console.ReadKey();

SocketWatch.Close();
}

/// <summary>
/// 监听客户端发来的请求
/// </summary>
private static void WatchConnecting()
{
Socket connection = null;

//持续不断监听客户端发来的请求
while (true)
{
try
{
connection = SocketWatch.Accept();
}
catch (Exception ex)
{
//提示套接字监听异常
Console.WriteLine(ex.Message);
break;
}

//客户端网络结点号
string remoteEndPoint = connection.RemoteEndPoint.ToString();
//添加客户端信息
ClientConnectionItems.Add(remoteEndPoint, connection);
//显示与客户端连接情况
Console.WriteLine("\r\n[客户端\"" + remoteEndPoint + "\"建立连接成功! 客户端数量:" + ClientConnectionItems.Count + "]");

//获取客户端的IP和端口号
IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

//让客户显示"连接成功的"的信息
string sendmsg = "[" + "本地IP:" + clientIP + " 本地端口:" + clientPort.ToString() + " 连接服务端成功!]";
byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
connection.Send(arrSendMsg);

//创建一个通信线程
Thread thread = new Thread(recv);
//设置为后台线程,随着主线程退出而退出
thread.IsBackground = true;
//启动线程
thread.Start(connection);
}
}
/// <summary>
/// 接收客户端发来的信息,客户端套接字对象
/// </summary>
/// <param name="socketclientpara"></param>
private static void recv(object socketclientpara)
{
Socket socketServer = socketclientpara as Socket;

while (true)
{
//创建一个内存缓冲区,其大小为1024*1024字节 即1M
byte[] arrServerRecMsg = new byte[1024 * 1024];
//将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
try
{
int length = socketServer.Receive(arrServerRecMsg);

//将机器接受到的字节数组转换为人可以读懂的字符串
string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

//将发送的字符串信息附加到文本框txtMsg上
Console.WriteLine("\r\n[客户端:" + socketServer.RemoteEndPoint + " 时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "]\r\n" + strSRecMsg);

//Thread.Sleep(3000);
//socketServer.Send(Encoding.UTF8.GetBytes("[" + socketServer.RemoteEndPoint + "]:"+strSRecMsg));
//发送客户端数据
if (ClientConnectionItems.Count > 0)
{
foreach (var socketTemp in ClientConnectionItems)
{
socketTemp.Value.Send(Encoding.UTF8.GetBytes("[" + socketServer.RemoteEndPoint + "]:" + strSRecMsg));
}
}
}
catch (Exception)
{
ClientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());
//提示套接字监听异常
Console.WriteLine("\r\n[客户端\"" + socketServer.RemoteEndPoint + "\"已经中断连接! 客户端数量:" + ClientConnectionItems.Count + "]");
//关闭之前accept出来的和客户端进行通信的套接字
socketServer.Close();
break;
}
}
}
#endregion

}
}

C#的Socket通信Demo

标签:开启   itop   space   包含   ddr   indexof   字节数组   console   client   

原文地址:https://www.cnblogs.com/zhaiganggang/p/13807173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!