使用Socket建立网络连接TCP版
2017-10-19 20:09
525 查看
TCPServer:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Collections.Generic;
using System.Net.NetworkInformation;
namespace TcpServer
{
class Program
{
static void Main(string[] args)
{
Server server = new Server();
server.StartUp();
while (true)
{
string str = Console.ReadLine();
server.SendAll(str);
}
}
}
public class Server
{
//配置相关
private string _ip = "192.168.30.35";
private int _port = 10000;
//服务器套接字
private Socket _server;
//接受客户端连接的线程,因为Accept是一个阻塞线程的方法,而且此方法还需要循环执行
private Thread _acceptClientConnectThread;
//所有已经连接的客户端
private List<Socket> _clientList = new List<Socket>();
/// <summary>
/// 启动服务器 = 建立流式套接字 + 配置本地地址
/// </summary>
public void StartUp()
{
try
{
//建立套接字 , 寻址方案,套接字类型,协议类型
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//_server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//配置本地地址
EndPoint endPoint = new IPEndPoint(GetIpv4(NetworkInterfaceType.Ethernet), _port);
_server.Bind(endPoint);
//监听和接受客户端请求
_server.Listen(30);
//开启一个接受连接的线程
_acceptClientConnectThread = new Thread(AcceptClientConnect);
_acceptClientConnectThread.Start();
Console.WriteLine("{0}:{1} StartUp...", _ip, _port);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// 接受客户端连接
/// </summary>
public void AcceptClientConnect()
{
while (true)
{
try
{
//接受客户端连接
Socket clientSocket = _server.Accept();
//维护一个客户端在线列表
_clientList.Add(clientSocket);
//获取客户端的网络地址标识
IPEndPoint clientEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
//输出一下地址和端口
Console.WriteLine("{0}:{1} Connect...", clientEndPoint.Address.ToString(), clientEndPoint.Port);
//接受客户端消息的线程
Thread acceptClientMsg = new Thread(AcceptMsg);
acceptClientMsg.Start(clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// 接受消息
/// </summary>
public void AcceptMsg(object obj)
{
//强转为Socket类型
Socket client = obj as Socket;
//字节数组 接受传来的信息 1024 * 64
byte[] buffer = new byte[client.ReceiveBufferSize];
//获取客户端的网络地址标识
IPEndPoint clientEndPoint = client.RemoteEndPoint as IPEndPoint;
try
{
while (true)
{
//接受消息
int len = client.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
Console.WriteLine("Receive {0} : {1} :{2}", clientEndPoint.Address.ToString(), _port, str);
}
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
_clientList.Remove(client);
}
}
/// <summary>
/// 给某一个客户端发送消息
/// </summary>
public void Send(string str, Socket client)
{
try
{
//string => byte[]
byte[] strBytes = Encoding.UTF8.GetBytes(str);
client.Send(strBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// 发送给所有人
/// </summary>
public void SendAll(string str)
{
for (int i = 0; i < _clientList.Count; i++)
{
Send(str, _clientList[i]);
}
}
/// <summary>
/// 获取Ip地址
/// </summary>
public IPAddress GetIpv4(NetworkInterfaceType type)
{
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
for (int i = 0; i < networkInterfaces.Length; i++)
{
if (type == networkInterfaces[i].NetworkInterfaceType && networkInterfaces[i].OperationalStatus == OperationalStatus.Up)
{
UnicastIPAddressInformationCollection ips = networkInterfaces[i].GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation item in ips)
{
if (item.Address.AddressFamily == AddressFamily.InterNetwork)
{
return item.Address;
}
}
}
}
return null;
}
/// <summary>
/// 关闭套接字
/// </summary>
public void Close()
{
if (_clientList.Count > 0)
{
for (int i = 0; i < _clientList.Count; i++)
{
_clientList[i].Close();
}
}
_clientList.Clear();
_server.Close();
_acceptClientConnectThread.Abort();
}
}
}
TCPClient:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace TcpClient
{
class Program
{
static void Main(string[] args)
{
Client client = new Client();
client.StartUp();
while (true)
{
string str = Console.ReadLine();
client.Send(str);
}
}
}
public class Client
{
private Socket _client;
private Thread _acceptServerMsg;
public void StartUp()
{
try
{
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//客户端连接
_client.Connect("192.168.30.35", 10000);
//接受消息的线程
_acceptServerMsg = new Thread(AcceptServerMsg);
_acceptServerMsg.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public void AcceptServerMsg()
{
byte[] buffer = new byte[1024 * 64];
while (true)
{
try
{
int len = _client.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
Console.WriteLine("Reveive Msg From Server : {0}", str);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// 发送消息
/// </summary>
public void Send(string str)
{
try
{
//string => byte[]
byte[] strBytes = Encoding.UTF8.GetBytes(str);
_client.Send(strBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// 关闭套接字
/// </summary>
public void Close()
{
if (_client.Connected)
{
_client.Close();
}
_acceptServerMsg.Abort();
}
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Collections.Generic;
using System.Net.NetworkInformation;
namespace TcpServer
{
class Program
{
static void Main(string[] args)
{
Server server = new Server();
server.StartUp();
while (true)
{
string str = Console.ReadLine();
server.SendAll(str);
}
}
}
public class Server
{
//配置相关
private string _ip = "192.168.30.35";
private int _port = 10000;
//服务器套接字
private Socket _server;
//接受客户端连接的线程,因为Accept是一个阻塞线程的方法,而且此方法还需要循环执行
private Thread _acceptClientConnectThread;
//所有已经连接的客户端
private List<Socket> _clientList = new List<Socket>();
/// <summary>
/// 启动服务器 = 建立流式套接字 + 配置本地地址
/// </summary>
public void StartUp()
{
try
{
//建立套接字 , 寻址方案,套接字类型,协议类型
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//_server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//配置本地地址
EndPoint endPoint = new IPEndPoint(GetIpv4(NetworkInterfaceType.Ethernet), _port);
_server.Bind(endPoint);
//监听和接受客户端请求
_server.Listen(30);
//开启一个接受连接的线程
_acceptClientConnectThread = new Thread(AcceptClientConnect);
_acceptClientConnectThread.Start();
Console.WriteLine("{0}:{1} StartUp...", _ip, _port);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// 接受客户端连接
/// </summary>
public void AcceptClientConnect()
{
while (true)
{
try
{
//接受客户端连接
Socket clientSocket = _server.Accept();
//维护一个客户端在线列表
_clientList.Add(clientSocket);
//获取客户端的网络地址标识
IPEndPoint clientEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
//输出一下地址和端口
Console.WriteLine("{0}:{1} Connect...", clientEndPoint.Address.ToString(), clientEndPoint.Port);
//接受客户端消息的线程
Thread acceptClientMsg = new Thread(AcceptMsg);
acceptClientMsg.Start(clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// 接受消息
/// </summary>
public void AcceptMsg(object obj)
{
//强转为Socket类型
Socket client = obj as Socket;
//字节数组 接受传来的信息 1024 * 64
byte[] buffer = new byte[client.ReceiveBufferSize];
//获取客户端的网络地址标识
IPEndPoint clientEndPoint = client.RemoteEndPoint as IPEndPoint;
try
{
while (true)
{
//接受消息
int len = client.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
Console.WriteLine("Receive {0} : {1} :{2}", clientEndPoint.Address.ToString(), _port, str);
}
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
_clientList.Remove(client);
}
}
/// <summary>
/// 给某一个客户端发送消息
/// </summary>
public void Send(string str, Socket client)
{
try
{
//string => byte[]
byte[] strBytes = Encoding.UTF8.GetBytes(str);
client.Send(strBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// 发送给所有人
/// </summary>
public void SendAll(string str)
{
for (int i = 0; i < _clientList.Count; i++)
{
Send(str, _clientList[i]);
}
}
/// <summary>
/// 获取Ip地址
/// </summary>
public IPAddress GetIpv4(NetworkInterfaceType type)
{
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
for (int i = 0; i < networkInterfaces.Length; i++)
{
if (type == networkInterfaces[i].NetworkInterfaceType && networkInterfaces[i].OperationalStatus == OperationalStatus.Up)
{
UnicastIPAddressInformationCollection ips = networkInterfaces[i].GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation item in ips)
{
if (item.Address.AddressFamily == AddressFamily.InterNetwork)
{
return item.Address;
}
}
}
}
return null;
}
/// <summary>
/// 关闭套接字
/// </summary>
public void Close()
{
if (_clientList.Count > 0)
{
for (int i = 0; i < _clientList.Count; i++)
{
_clientList[i].Close();
}
}
_clientList.Clear();
_server.Close();
_acceptClientConnectThread.Abort();
}
}
}
TCPClient:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace TcpClient
{
class Program
{
static void Main(string[] args)
{
Client client = new Client();
client.StartUp();
while (true)
{
string str = Console.ReadLine();
client.Send(str);
}
}
}
public class Client
{
private Socket _client;
private Thread _acceptServerMsg;
public void StartUp()
{
try
{
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//客户端连接
_client.Connect("192.168.30.35", 10000);
//接受消息的线程
_acceptServerMsg = new Thread(AcceptServerMsg);
_acceptServerMsg.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public void AcceptServerMsg()
{
byte[] buffer = new byte[1024 * 64];
while (true)
{
try
{
int len = _client.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
Console.WriteLine("Reveive Msg From Server : {0}", str);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// 发送消息
/// </summary>
public void Send(string str)
{
try
{
//string => byte[]
byte[] strBytes = Encoding.UTF8.GetBytes(str);
_client.Send(strBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// 关闭套接字
/// </summary>
public void Close()
{
if (_client.Connected)
{
_client.Close();
}
_acceptServerMsg.Abort();
}
}
}
相关文章推荐
- .Net网络编程——使用TcpClient与TcpListener建立客户端与服务端连接
- TCP连接的三次握手和Socket建立网络连接的步骤
- 【网络通信】服务器端Socket监听80端口,建立连接传输数据时也是使用的80端口么?
- CocoaAsyncSocket网络通信使用之tcp连接(一)
- 图说使用socket建立TCP连接
- TCP连接的三次握手和Socket建立网络连接的步骤
- CocoaAsyncSocket网络通信使用之tcp连接
- CocoaAsyncSocket网络通信使用之tcp连接(一)
- Swift代码使用GCDAsyncSocket库建立TCP连接失败。
- .Net网络编程——使用TcpClient与TcpListener建立客户端与服务端连接
- 使用pb的connection对象建立TCP连接
- .net连接Sql时出现"已成功与服务器建立连接,但是在登录过程中发生错误。 (provider: TCP 提供程序, error: 0 - 指定的网络名不再可用。) "
- 使用GPRS的cmwap接入点实现网络通讯1-----建立连接
- 基于TCP的网络游戏黑白棋系列(一):建立连接
- 请教:C#网络编程相关的知识,建立socket服务器时向客户端连接,就建立不了了?
- 在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架
- 在vb中使用Iphlpapi.dll获取网络信息 第二章 第十七节 设置TCP连接状态
- 网络编程基础:使用TCP连接
- 在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架(一)----基础类库部分
- 在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架(一)----基础类库部分