.net socket代码
时间: 2024-01-31 09:03:53 浏览: 127
.net socket客户端实例代码分享
以下是使用C#编写的简单的Socket服务器和客户端代码:
服务器端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
// 创建一个IP地址和端口号
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8888;
// 创建一个Socket对象
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定Socket对象到IP地址和端口号上
serverSocket.Bind(new IPEndPoint(ip, port));
// 开始监听客户端连接请求
serverSocket.Listen(10);
Console.WriteLine("等待客户端连接...");
// 接受客户端连接请求
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("客户端连接成功!");
// 向客户端发送消息
byte[] buffer = Encoding.UTF8.GetBytes("欢迎连接到服务器!");
clientSocket.Send(buffer);
// 接收客户端发送的消息
buffer = new byte[1024];
int length = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, length);
Console.WriteLine("接收到客户端消息:" + message);
// 关闭Socket连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
serverSocket.Close();
Console.ReadLine();
}
}
}
```
客户端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketClient
{
class Program
{
static void Main(string[] args)
{
// 创建一个IP地址和端口号
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8888;
// 创建一个Socket对象
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接到服务器
clientSocket.Connect(new IPEndPoint(ip, port));
// 接收服务器发送的消息
byte[] buffer = new byte[1024];
int length = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, length);
Console.WriteLine("接收到服务器消息:" + message);
// 向服务器发送消息
message = "你好,服务器!";
buffer = Encoding.UTF8.GetBytes(message);
clientSocket.Send(buffer);
// 关闭Socket连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
Console.ReadLine();
}
}
}
```
阅读全文