*
当前实例只是简单的完成了一个服务器对一个客户,只能一对一,一对多会发生错误 一对多需要把连接进来的socket对象放入一个集合中
*
导入.net
以及.net.sockets
//创建一个服务器类,
1.创建一个服务器通信,三个参数
2.IPEndPoint(ipAddress.parse(string ip),port);//传入ip地址以及端口号
3.bind
4.监听 listen
5.Accept//接收客户端的请求
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace Demo2048.网络通信
{
class ServerDemo
{
Socket server;
Socket user;
bool isCreate;
public ServerDemo(string ip,int port) {
server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
server.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
server.Listen(0);//参数为0表示不限制连接进来的数量
Console.WriteLine("等待用户的连接");
isCreate = true;
}
catch (Exception e) {
Console.WriteLine("ip格式不对");
}
}
public void Start() {
if (!isCreate) {
Console.WriteLine("启动失败");
return;
}
user=server.Accept();//接收并返回连接成功客户端套接字
Console.WriteLine("用户链接成功");
System.Threading.Thread th = new System.Threading.Thread(Recevie);
th.Start();
this.Send();
}
public void Recevie() {//接收客户端发回的消息
while (true) {
byte[] arr = new byte[1024 * 100];
int num=user.Receive(arr);
Console.WriteLine("用户:{0}", Encoding.Default.GetString(arr, 0, num));
}
}
public void Send() {//发送消息给客户端
while (true) {
user.Send(Encoding.Default.GetBytes(Console.ReadLine()));
}
}
}
}
//创建一个客户端类
1.创建一个客户端通信,三个参数,与服务器对应
2.连接
Class Client{
Socket client;
public Client(string ip, int port)
{
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
client.Connect(point);
Console.WriteLine("连接服务器");
}
catch (FormatException e) {
Console.WriteLine("不是有效路径");
}
catch (Exception e)
{
Console.WriteLine("未找到制定的服务器");
}
}
public void Start(){
Thread th =new Thread(ReceiveMessage);
th.Start;
this.SendMessage();
}
public void SendMessage(){
while(true){
string value =Console.readLine();
byte[] data =Encoding.UTf8.GetBytes(value);
client.Send(data,0,data.length);
}
}
//接收服务器消息
public void ReceiveMessage()
{
try
{
while (true)
{
byte[] data = new byte[1024];
int num = client.Receive(data);
string value = Encoding.UTF8.GetString(data, 0, num);
Console.WriteLine("服务器说:" + value);
}
}
catch (Exception e)
{
Console.WriteLine("与服务器断开连接");
}
}
}
//实现类
class Program
{
static void Main(string[] args)
{
Client client = new Client("192.168.88.93",8888);
client.Start();
}
}
“`