服务端的搭建
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace TCP服务器
{
class Program
{
static void Main(string[] args)
{
//第一步创建socket对象 服务端
Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//第二步绑定ip和端口号
//这是自身电脑的ip,Parse可以直接转换为IPAddress的对象出去
IPAddress ipAddress = IPAddress.Parse("192.168.1.105");
//92代表端口号
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 92);
//绑定
serverSocket.Bind(ipEndPoint);
//客户端个数
serverSocket.Listen(0);
//创建客户端
Socket clientSocket = serverSocket.Accept();//接受一个客户端连接
//选客户端发送一条消息
string msg = "Hello client! 你好.....";
//System.Text.Encoding.UTF8.GetBytes将一个字符串转为byte的序列
byte[] data = System.Text.Encoding.UTF8.GetBytes(msg);
clientSocket.Send(data);
//接受客户端的一条消息
byte[] dataBuffer = new byte[1024];//用来接受数据
//接收到的消息将存入dataBuffer中,返回接收到了多少个数据
int count = clientSocket.Receive(dataBuffer);
//0到count个数据的内容
string msgReceive = System.Text.Encoding.UTF8.GetString(dataBuffer,0,count);
Console.WriteLine(msgReceive);
//在客户端反馈消息后,暂停下
Console.ReadKey();
//先关闭客户端,在关闭服务端
clientSocket.Close();
serverSocket.Close();
}
}
}
客户端的搭建
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace TCP客户端
{
class Program
{
static void Main(string[] args)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//服务端链接ip与端口号
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.105"), 92));
byte[] data = new byte[1024];
int count = clientSocket.Receive(data);
string msg = Encoding.UTF8.GetString(data, 0, count);
Console.Write(msg);
string s = Console.ReadLine();
Console.Write(s);
clientSocket.Send(Encoding.UTF8.GetBytes(s));
Console.ReadKey();
clientSocket.Close();
}
}
}

本文介绍了如何使用C#语言搭建TCP服务端及客户端,包括服务端的创建和客户端的连接,实现双方的消息收发功能。
4177

被折叠的 条评论
为什么被折叠?



