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
0
投稿
猜你喜欢
Android本地验证码的生成代码
2023-05-03 18:44:02
SpringBoot定时任务多线程实现示例
2021-10-06 08:45:18
Java8生成时间方式及格式化时间的方法实例
2021-07-28 19:58:52
一种类似JAVA线程池的C++线程池实现方法
2021-11-02 21:31:52
C#多线程中的互斥锁Mutex
2022-04-26 06:11:55
java并发JUC工具包AtomicInteger原子整型语法基础
2023-10-05 14:16:47
Android 根据手势顶部View自动展示与隐藏效果
2022-01-11 07:30:20
本地jvm执行flink程序带web ui的操作
2022-09-03 20:49:00
springboot集成springsecurity 使用OAUTH2做权限管理的教程
2023-12-22 22:57:21
C#中事务处理和非事务处理方法实例分析
2023-12-23 08:09:13
Spring Boot深入排查 java.lang.ArrayStoreException异常
2023-07-11 16:31:27
LZ77压缩算法原理的理解
2023-01-16 17:48:02
Spring Cloud Hystrix 线程池队列配置(踩坑)
2023-12-18 16:13:22
android TextView设置中文字体加粗实现方法
2023-08-06 02:32:03
Spring Cloud Alibaba Nacos Config进阶使用
2021-07-14 19:46:00
C#迷你猜数实例分析
2023-11-02 16:10:49
SpringCloud Eureka应用全面介绍
2022-08-23 17:43:26
Java多线程 两阶段终止模式Two-Phase Termination Patter
2023-11-29 04:47:04
java处理按钮点击事件的方法
2021-08-24 16:28:10
浅谈java中String与StringBuffer的不同
2021-11-24 11:54:12