客户端
using System;
using System.Net;
using System.Net.Sockets;
namespace Socket_Client
{
class Program
{
static void Main(string[] args)
{
//1、创建Socket对象(和服务端进行通信)
Socket ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//2、连接服务器
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.96.19"),8055);
ClientSocket.Connect(endPoint);
byte[] data = new byte[1024];//用于测试
//3、发送
ClientSocket.Send(data);
//4、接收
ClientSocket.Receive(data);
//关闭
//ClientSocket.Close();
}
}
}
服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Socket_SeverTcp
{
class Program
{
static void Main(string[] args)
{
//1、创建服务端Socket对象(负责监听客户端)
Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddress = IPAddress.Parse("192.168.96.19");//这边这个要改成自己的本机IP地址
EndPoint endpoint = new IPEndPoint(ipaddress,8055);
//2、绑定端口
ServerSocket.Bind(endpoint);
Console.WriteLine("... 启动服务器成功");
//3、监听
ServerSocket.Listen(100);//监听的长度(比如上厕所有5个坑,有20个人,另外15个就要排队,这里留了100个坑)
Console.WriteLine("... 开始监听");
while (true)//死循环,一直执行监听
{
//4、等待接收客户端连接(返回用于和客户端通信的Socket)//从这里可以看到服务端的两个Socket都出来了
Socket newSocket = ServerSocket.Accept();
Console.WriteLine("连接到一个客户端:"+newSocket.RemoteEndPoint);
//这是举例,我们发的是字节但我们肉眼可见的是字符串,这边是为了语法对
byte[] data = new byte[1024];
//5、接收消息
newSocket.Receive(data);
//6、发送
newSocket.Send(data);
//7、关闭
//newSocket.Close();
}
}
}
}