C#中Socket通信用法实例详解
作者:我心依旧 发布时间:2022-07-10 03:42:03
标签:C#,Socket
本文实例讲述了C#中Socket通信用法。分享给大家供大家参考。具体如下:
一、UDP方式:
服务器端代码:
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
newsock.Bind(ipep);//Socket与本地的一个终结点相关联
Console.WriteLine("Waiting for a client..");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
EndPoint Remote = (EndPoint)(sender);//
recv = newsock.ReceiveFrom(data, ref Remote);//接受数据
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to my test server!";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
while (true)
{
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
客户端代码:
void MainInfo()
{
byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.21"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello,are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true)//读取数据
{
input = richTextBox1.Text;//从键盘读取数据
if (input == "text")//结束标记
{
break;
}
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping client");
server.Close();
}
二、TCP方式:
服务器端代码:
Socket serverSocket = null;
Thread clientThread = null;
Socket clientSocket = null;
Thread thread = null;
IPAddress ips = null;
PEndPoint ipep = null;
void ServerStart()
{
ips = Dns.GetHostAddresses(Dns.GetHostName())[0];
//创建IPEndPoint实例
ipep = new IPEndPoint(ips, 9050);
//创建一个套接字
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//将所创建的套接字与IPEndPoint绑定
serverSocket.Bind(ipep);
//设置套接字为收听模式
serverSocket.Listen(20);
while (listenalive)
{
try
{
//在套接字上接收接入的连接
clientSocket = serverSocket.Accept();
clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
clientThread.Start(clientSocket);
}
catch (Exception ex)
{
WriteErrorLog(ex.Message);
serverSocket.Close();
serverSocket = null;
}
}
}
static void ReceiveData(object obj)
{
bool keepalive = true;
Socket s = obj as Socket;
Byte[] buffer = new Byte[1024];
//根据收听到的客户端套接字向客户端发送信息
IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
Console.WriteLine("客户端ip:" + clientep.Address + " 端口:" + clientep.Port);
string welcome = "连接服务器成功";
buffer = System.Text.Encoding.Unicode.GetBytes(welcome);
//向客户端发送“连接服务器成功”消息
s.Send(buffer, buffer.Length, SocketFlags.None);
buffer = new Byte[1024];
int bufLen = 0;
string content = string.Empty;
while (true)
{
//在套接字上接收客户端发送的信息
bufLen = 0;
try
{
bufLen = s.Receive(buffer);
if (bufLen == 0)
{
break;
}
content += System.Text.Encoding.Unicode.GetString(buffer, 0, bufLen);
}
catch (Exception ex)
{
break; ;
}
}
Send(s, content);
s = null;
buffer = null;
clientep = null;
Thread.CurrentThread.Abort();
}
客户端代码:
void Send(string content)
{
byte[] data = new byte[1024];
newclient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
ie = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ipadd), port);//服务器的IP和端口
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
newclient.Connect(ie);
}
catch (System.Net.Sockets.SocketException e)
{
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
//连接服务器成功
string stringdata = System.Text.Encoding.Unicode.GetString(data, 0, recv);
if (stringdata == "连接服务器成功")
{
newclient.Send(System.Text.Encoding.Unicode.GetBytes(content));
newclient.Shutdown(System.Net.Sockets.SocketShutdown.Send);
data = new byte[1024];
recv = newclient.Receive(data);
string result = System.Text.Encoding.Unicode.GetString(data, 0, recv);
newclient.Shutdown(System.Net.Sockets.SocketShutdown.Receive);
newclient.Close();
MessageBox.Show(result);
}
else
{
MessageBox.Show("连接服务器失败", "友情提示");
}
}
希望本文所述对大家的C#程序设计有所帮助。
0
投稿
猜你喜欢
- Java super关键字super 关键字与 this 类似,this 用来表示当前类的实例,super 用来表示父类。super 可以用
- 本文实例讲述了java计算给定字符串中出现次数最多的字母和该字母出现次数的方法。分享给大家供大家参考,具体如下:import Java.ut
- 下载:1.在spring-mvc中配置(用于100M以下的文件下载)<bean class="org.springframe
- 线程安全解决方案synchronized,ReentrantLock,Atomic 使用场景描述在实际开发过程中如果服务量,请求频繁,就会经
- 场景发布微服务的操作一般都是打完新代码的包,kill掉在跑的应用,替换新的包,启动。spring cloud 中使用eureka为注册中心,
- 上标是指比同一行中其他文字稍高的文字,而下标是指比同一行中其他文字稍低的文字。在生活中,我们常见的平方米、立方米等符号以及化学中的各种元素符
- 主要介绍springboot项目中配置文件的加密前言为了保证服务器相关信息的保密,一般会采用加密的方式进行对配置文件原文的加密,今天介绍下s
- 一、实现了Aware的接口Spring中有很多继承于aware中的接口,这些接口到底是做什么用到的,下面我们就一起来看看吧。Aware 接口
- 目录前言导入okhttp3方法简介两种版本超时设置用法总结前言okhttp是一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支
- mybatis 3 | 参考文档MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几
- 封装类用于阻止系统休眠的C#类。以下是代码注释的解释:DllImport("kernel32.dll"):定义了一个AP
- 这几天做项目,有些地方的图片需要用到圆形图片,所以百度了一下,在github上找到一个开源项目,处理很简单,效果如下:使用起来特别简单,一共
- MVC三层架构我们在刚刚成为程序员的时候,就会被前辈们 “教育” 说系统的设计要遵循 MVC(Model-View-Controller)架
- 前台form 表单:设置method=post,enctype=multipart/form-data。struts2在原有的上传解析器继承
- SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):cache – 对给定命名空间的缓存配置。cache-ref – 对其他命
- 题目要求思路一:暴力模拟由于数据范围不算离谱,所以直接遍历解决可行。Javaclass Solution { pu
- 阻塞、无饥饿、无障碍、无锁、无等待几种。阻塞一个线程是阻塞的,那么在其他线程释放资源之前,当前线程无法继续执行。当我们使用synchroni
- 因为在Action的execute方法声明时就抛出了Exception异常,所以我们无需再execute方法中捕捉异常,仅需在struts.
- springboot启动时自动加载application.properties或者application.yml,如何定义自己的配置让spr
- 目录 - JWT- JWT与其它的区别OAuthCookie/Session Auth- JWT的优点- 认证- JWT的缺点-