C#中Socket的简单使用

C#中Socket的简单使用以前学过的Socket,后来没怎么用过,就基本忘了,所以闲来时重新回顾学习一番.一.Socket的概念Socket其实并不是一个协议,而是为了方便使用TCP或UDP而抽象出来的一层,是位于应用层和传

大家好,又见面了,我是你们的朋友全栈君。

以前学过的Socket,后来没怎么用过,就基本忘了,所以闲来时重新回顾学习一番.

一.Socket的概念
Socket其实并不是一个协议,而是为了方便使用TCP或UDP而抽象出来的一层,是位于应用层和传输控制层之间的一组接口.

当两台主机通信是,必须通过Socket连接,Socket则利用TCP/IP协议建立TCP连接.TCP连接则更依赖于底层的IP协议.Socket是控制层传输协议.

双向的通信连接实现数据的交换,连接的一端成为一个Socket.

 <span role="heading" aria-level="2">C#中Socket的简单使用

 

 

二.网络通信三要素
IP地址(网络上主机设备的唯一标识)
端口号(定位程序)
有效端口:0~65535,其中0~1024由系统使用,开发中一般使用1024以上端口.
传输协议(用什么样的方式进行交互)
常见协议:TCP(面向连接,提供可靠的服务),UDP(无连接,传输速度快)
三.Socket的通信流程

<span role="heading" aria-level="2">C#中Socket的简单使用

 

 

四.C#中Socket的简单使用步骤
第一步:服务端监听某个端口

第二步:客户端向服务端地址和端口发起Socket请求

第三步:服务器接收连接请求后创建Socket连接,并维护这个连接队列

第四步:客户端和服务端就建立起了双工同信,客户端与服务端就可以实现彼此发送消息

五.简单代码实例

1.服务端代码

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

namespace SocketUtil
{
public class SocketServer
{
private string _ip = string.Empty;
private int _port = 0;
private Socket _socket = null;
private byte[] buffer = new byte[1024 * 1024 * 2];
/// <summary>
/// 构造函数
/// </summary>
/// <param name=”ip”>监听的IP</param>
/// <param name=”port”>监听的端口</param>
public SocketServer(string ip, int port)
{
this._ip = ip;
this._port = port;
}
public SocketServer(int port)
{
this._ip = “0.0.0.0”;
this._port = port;
}

public void StartListen()
{
try
{
//1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.0 创建IP对象
IPAddress address = IPAddress.Parse(_ip);
//3.0 创建网络端口,包括ip和端口
IPEndPoint endPoint = new IPEndPoint(address, _port);
//4.0 绑定套接字
_socket.Bind(endPoint);
//5.0 设置最大连接数
_socket.Listen(int.MaxValue);
Console.WriteLine(“监听{0}消息成功”, _socket.LocalEndPoint.ToString());
//6.0 开始监听
Thread thread = new Thread(ListenClientConnect);
thread.Start();

}
catch (Exception ex)
{
}
}
/// <summary>
/// 监听客户端连接
/// </summary>
private void ListenClientConnect()
{
try
{
while (true)
{
//Socket创建的新连接
Socket clientSocket = _socket.Accept();
clientSocket.Send(Encoding.UTF8.GetBytes(“服务端发送消息:”));
Thread thread = new Thread(ReceiveMessage);
thread.Start(clientSocket);
}
}
catch (Exception)
{
}
}

/// <summary>
/// 接收客户端消息
/// </summary>
/// <param name=”socket”>来自客户端的socket</param>
private void ReceiveMessage(object socket)
{
Socket clientSocket = (Socket)socket;
while (true)
{
try
{
//获取从客户端发来的数据
int length = clientSocket.Receive(buffer);
Console.WriteLine(“接收客户端{0},消息{1}”, clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
}
}
}

2.客户端代码

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 SocketUtil
{
public class SocketClient
{
private string _ip = string.Empty;
private int _port = 0;
private Socket _socket = null;
private byte[] buffer = new byte[1024 * 1024 * 2];

/// <summary>
/// 构造函数
/// </summary>
/// <param name=”ip”>连接服务器的IP</param>
/// <param name=”port”>连接服务器的端口</param>
public SocketClient(string ip, int port)
{
this._ip = ip;
this._port = port;
}
public SocketClient(int port)
{
this._ip = “127.0.0.1”;
this._port = port;
}

/// <summary>
/// 开启服务,连接服务端
/// </summary>
public void StartClient()
{
try
{
//1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.0 创建IP对象
IPAddress address = IPAddress.Parse(_ip);
//3.0 创建网络端口包括ip和端口
IPEndPoint endPoint = new IPEndPoint(address, _port);
//4.0 建立连接
_socket.Connect(endPoint);
Console.WriteLine(“连接服务器成功”);
//5.0 接收数据
int length = _socket.Receive(buffer);
Console.WriteLine(“接收服务器{0},消息:{1}”, _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer,0,length));
//6.0 像服务器发送消息
for (int i = 0; i < 10; i++)
{
Thread.Sleep(2000);
string sendMessage = string.Format(“客户端发送的消息,当前时间{0}”, DateTime.Now.ToString());
_socket.Send(Encoding.UTF8.GetBytes(sendMessage));
Console.WriteLine(“像服务发送的消息:{0}”, sendMessage);
}
}
catch (Exception ex)
{
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
Console.WriteLine(ex.Message);
}
Console.WriteLine(“发送消息结束”);
Console.ReadKey();
}
}
}

3.分别开启客户端和服务端

using SocketUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SocketClientApp
{
class Program
{
static void Main(string[] args)
{
SocketClient client = new SocketClient(8888);
client.StartClient();
Console.ReadKey();
}
}
}

using SocketUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SocketServerApp
{
class Program
{
static void Main(string[] args)
{
SocketServer server = new SocketServer(8888);
server.StartListen();
Console.ReadKey();
}
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154405.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Vue(27)vue-codemirror实现在线代码编译器「建议收藏」

    Vue(27)vue-codemirror实现在线代码编译器「建议收藏」前言如果我们想在Web端实现在线代码编译的效果,那么需要使用组件vue-codemirror,他是将CodeMirror进行了再次封装支持代码高亮62种主题颜色,例如monokai等等支持js

    2022年7月29日
    43
  • c语言system返回信息,理解c语言system函数的返回值

    c语言system返回信息,理解c语言system函数的返回值作者:新浪微博(@NP等不等于P)计算机学习微信公众号(jsj_xx)c语言中的system函数可以说是程序执行时的一道重生之门,其重生妙效犹如我们之前《透析硬链接和软链接的区别》一文中的软链接文件。然而,system函数也带来了判断返回值的烦恼!本文分享我们对system函数的返回值的理解,希望对c语言学习者有所帮助(如有错误,还望指正,谢谢)。先给出我们理解的system函数执行原理:fork…

    2022年9月18日
    0
  • C语言基础:函数的定义与调用[通俗易懂]

    C语言基础:函数的定义与调用[通俗易懂]    在前面内容中我们调用了一个标准C的库函数,叫printf,那么如果我们想自己定义函数应该如何来编写程序呢?定义函数又有什么好处呢?因为我们在教材中提及到的例子主要目的是为了让读者对程序的原理有一定的了解,所以设定的例子程序通常都比较简单,基本上在几行到十几行,多一点的也就三五十行代而已,但是在真正的编程工作中,我们需要完成的代码将非常大,所以将代码合理的分为不同的区块是很有必要的,…

    2022年6月30日
    29
  • 中国移动校园WLAN客户端及使用方法「建议收藏」

    中国移动校园WLAN客户端及使用方法「建议收藏」学校终于覆盖了移动WLAN,坑爹的是信息中心没有给任何使用说明,给很多同学使用造成了障碍,现在把使用方法做一个简单的总结。文章中软件打包下载:http://pan.baidu.com/share/l

    2022年7月3日
    59
  • 2020 java实习生面试题总结「建议收藏」

    2020实习面试题总结:本人是广州某高校大四的一名学生,下面是12月份的面试总结一)hr的提问:1.自我介绍(必须的)2.职业规划3.你对我们企业了解吗4.

    2022年4月7日
    123
  • Windows下LaTeX安装教程与新手入门[通俗易懂]

    Windows下LaTeX安装教程与新手入门[通俗易懂]一、安装教程参考链接:https://blog.csdn.net/jackandsnow/article/details/88407909二、入门教程https://blog.csdn.net/Emily_Buffy/article/details/90180909写的非常详细,也很实用…

    2022年5月4日
    59

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号