服务器端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SocketToChatServer
{
class Program
{
static void Main(string[] args)
{
//创建socket 使用内网 流形式 tcp协议
Socket tcpServer = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//绑定ip,和端口号
IPAddress ipaddress = new IPAddress(new byte[] { 192,168,2,102});
EndPoint point = new IPEndPoint(ipaddress,7788); //ipendpoint是对ip+端口号封装的一个类
tcpServer.Bind(point); //想操作系统申请一个可用的ip和端口号,用来做通信
//开始监听(等待客户端连接)
tcpServer.Listen(100); //表示最大连接数为100个
Console.WriteLine("开始监听");
Socket clientSocket=tcpServer.Accept(); //暂停当前线程,知道有一个客户端连接过来,之后进行下面的代码
Console.WriteLine("一个客户端连接过来了");
//使用返回的socket跟客户端做通信
string message = "你好,牛是方的";
byte[] data= Encoding.UTF8.GetBytes(message); //对字符串做编码,得到一个字符串的字符数组
clientSocket.Send(data);
Console.WriteLine("向客户端发送了一条数据");
byte[] data2 = new byte[1024]; //创建一个字节数组用来当做容器,去承接客户端发送过来的数据
int length = clientSocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2,0,length); //把字节数据转化成一个字符串
Console.WriteLine("接受到了一个从客户端发送过来消息:" + message2);
Console.ReadKey();
}
}
}
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SocketToChatClint
{
class Program
{
static void Main(string[] args)
{
//创建一个socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//发起建立连接的请求
IPAddress ipaddress = IPAddress.Parse("192.168.2.102");
EndPoint point = new IPEndPoint(ipaddress,7788);
tcpClient.Connect(point); //通过Ip和端口号定位一个要连接到的服务器端
byte[] data = new byte[1024];
int length= tcpClient.Receive(data); //length返回值表示接受了多少字节的数据
string message= Encoding.UTF8.GetString(data,0,length); //0表示从取到数据的0号索引,length表示取到length长度的最大索引
Console.WriteLine(message);
//向服务器端发送消息
string message2 = Console.ReadLine(); //读取用户的输入,把输入的发送到服务器端
tcpClient.Send(Encoding.UTF8.GetBytes(message2)); //把字符串转化成字节数组,然后发送到服务器端
Console.ReadKey();
}
}
}