一步一步实现.NET下的Socket通信编程
【IT168 技术文档】
4、 在SocketLibrary项目中新建类Connection。表示一个连接,增加两个属性NetWorkStream和ConnectionName。分别表示一个连接的名字和它包含的NetWorkStream。源代码如下:
5、 新建一个继承自CollectionBase的类ConnectionCollection。用于保存Connection集合。
using System;
using System.Net;
using System.Net.Sockets;
namespace SocketLibrary

...{
public class Connection

...{

public NetworkStream NetworkStream ...{

get...{return _networkStream;}

set...{_networkStream = value;}
}
private NetworkStream _networkStream;

public string ConnectionName ...{

get...{return _connectionName;}

set...{_connectionName = value;}
}
private string _connectionName;
public Connection(NetworkStream networkStream,string connectionName)

...{
this._networkStream = networkStream;
this._connectionName = connectionName;
}
public Connection(NetworkStream networkStream):

this(networkStream,string.Empty) ...{ }
}
}
6、 新建一个类,名字为Server,用于侦听网络连接。
using System;

namespace SocketLibrary ...{

public class ConnectionCollection:System.Collections.CollectionBase ...{

public ConnectionCollection() ...{}

public void Add(Connection value) ...{
List.Add(value);
}

public Connection this[int index] ...{

get ...{
return List[index] as Connection;
}

set...{
List[index] = value;
}
}

public Connection this[string connectionName] ...{

get ...{

foreach(Connection connection in List) ...{
if(connection.ConnectionName == connectionName)
return connection;
}
return null;
}
}
}
}
using System;
using System.net;
using System.Net.Sockets;
namespace SocketLibrary

...{
public class Server

...{

public ConnectionCollection Connections ...{

get...{return _connections;}

set...{_connections = value;}
}
private ConnectionCollection _connections;
private TcpListener _listener;
public Server(TcpListener listener)

...{
this._connections = new ConnectionCollection();
this._listener = listener;
}

public void Start() ...{

while(true) ...{

if(_listener.Pending()) ...{
TcpClient client = _listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
this._connections.Add(new Connection(stream));
}
}
}
}
}
8、 在SocketFactory类中加入StartServer方法。当执行此方法时,初始化_ serverListenThread并在此线程中开始侦听网络连接。

public void StartServer(int port) ...{
TcpListener listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Server server = new Server(listener);
_serverListenThread = new System.Threading.Thread
(new System.Threading.ThreadStart(server.Start));
_serverListenThread.Start();
}