案例描述:利用socket实现联网交互功能
-------------------------------------------------持续更新--------------------------------------------------------
- 【服务端】
- Program脚本入口类:
using System;
using MyServer;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-----------Server.Start-------------");
Server server = new Server("xxx.xxx.1.105",10000);
server.StartFound();
Console.ReadKey();
}
}
- MyServer空间下Server脚本类:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
/*
* 1.先想好建立什么类,该类具有什么样的功能。
* 2.声明类,先写方法,后通过方法来写字段和属性。
* 3.
*/
namespace MySpace
{
#region
/// <summary>
/// 一、
/// 1.如何创建一个服务端
/// 2.如何创建一个客户端
/// 3.如何让他们连接起来
///
/// 二、
/// 1.他们之间如何发送数据、接受数据
/// 2.以什么方式发送和接收
///
/// 三、
/// 1.如何优化客户端、服务端
/// 2.
///
/// </summary>
public class Server
{
/// <summary>
/// 字段-声明变量socket对象
/// </summary>
Socket socket;
/// <summary>
/// 储存客户端对象
/// </summary>
private Socket client;
/// <summary>
/// IP好
/// </summary>
private string ip;
/// <summary>
/// 端口号
/// </summary>
private int port;
/// <summary>
/// 在实例化服务端时的构造函数
/// </summary>
public Server(string _ip,int _port)
{
ip = _ip;
port = _port;
}
/// <summary>
/// 服务端建立行为
/// </summary>
public void StartFound()
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip),port);
socket.Bind(iep);
socket.Listen(1000);
Console.WriteLine("服务端开启成功!");
Console.WriteLine("监视客户端的连接!");
//有阻塞效果,并且获得客户端的实例
client = socket.Accept();
//接收客户端的消息
}
catch (Exception e)
{
Console.WriteLine("服务端开启失败!");
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 服务端的接受行为
/// </summary>
public void Receive()
{
}
}
#endregion
}
- 【客户端】
- Program脚本入口类:
using System;
using MyClient;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-----------Clinet.Start-------------");
Client client = new Client();
client.ConnectServer();
Console.ReadKey();
}
}
- MyClient空间下Client脚本类:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
/*
* 其实客户端和服务器的实现都利用socket对象来实现
*
*/
namespace MyClient
{
#region
/*
*
*
*
*
*
*
*/
public class Client
{
/// <summary>
/// 声明socket对象
/// </summary>
Socket socket;
/// <summary>
/// 客户端对象的节点数据
/// </summary>
IPEndPoint iep;
public Client()
{
}
public void ConnectServer()
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
iep = new IPEndPoint(IPAddress.Parse("xxx.xxx.1.105"), 10000);
socket.Connect(iep);
Console.WriteLine("连接服务器成功!");
}
catch (Exception e)
{
Console.WriteLine("连接服务器失败!");
}
}
}
#endregion
}
运行结果: