C#中Socket通信用法实例详解
作者:我心依旧 时间:2022-07-10 03:42:03
本文实例讲述了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#程序设计有所帮助。
标签:C#,Socket
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring使用AOP完成统一结果封装实例demo
2021-12-16 18:49:06
![](https://img.aspxhome.com/file/2023/0/71630_0s.png)
C#实现单词本功能
2021-11-06 13:08:23
![](https://img.aspxhome.com/file/2023/0/79080_0s.png)
推荐史上最全的IDEA好用插件
2023-02-22 21:35:04
![](https://img.aspxhome.com/file/2023/8/62378_0s.png)
Mybatis一对多查询的两种姿势(值得收藏)
2023-07-01 00:20:08
![](https://img.aspxhome.com/file/2023/9/61669_0s.png)
详解Java线程池队列中的延迟队列DelayQueue
2023-08-30 01:22:04
Java的引用类型常用的四种方法
2023-11-29 14:05:24
![](https://img.aspxhome.com/file/2023/9/60349_0s.png)
Spring Boot Admin 进行项目监控管理的方法
2021-09-01 23:39:19
![](https://img.aspxhome.com/file/2023/1/67001_0s.png)
详解如何在SpringBoot项目中使用统一返回结果
2023-10-30 16:41:21
![](https://img.aspxhome.com/file/2023/4/58714_0s.png)
Java反射(Class类,Class对象获取)
2021-06-27 05:55:24
![](https://img.aspxhome.com/file/2023/4/63444_0s.png)
java应用占用内存过高排查的解决方案
2023-09-21 12:47:30
![](https://img.aspxhome.com/file/2023/4/77464_0s.jpg)
新手初学Java集合框架
2022-10-06 03:01:51
详解java整合solr5.0之solrj的使用
2023-07-23 03:12:06
![](https://img.aspxhome.com/file/2023/3/57493_0s.png)
Java实现人机猜拳小游戏
2023-10-07 16:11:37
![](https://img.aspxhome.com/file/2023/1/58681_0s.jpg)
C# 特殊的string类型详解
2022-02-10 14:11:59
Mybatis返回int或者Integer类型报错的解决办法
2023-08-09 02:41:14
springBoot项目如何实现启动多个实例
2021-09-22 00:13:47
![](https://img.aspxhome.com/file/2023/0/70500_0s.png)
详解Spring Bean的集合注入和自动装配
2023-02-18 15:02:58
![](https://img.aspxhome.com/file/2023/9/60829_0s.jpg)
Java几种常用的断言风格你怎么选
2021-10-30 23:30:32
浅谈Java中ArrayList线程不安全怎么办
2023-10-02 19:24:56
Java 集合框架之List 的使用(附小游戏练习)
2023-11-24 10:33:40
![](https://img.aspxhome.com/file/2023/7/59947_0s.png)