new tcpip

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TcpIp
{
    public class SocketClient
    {
        byte[] buffer = new byte[2048];
        Socket socket;
        Thread thread;
        string ip, port;
        public bool connect(string ip, string port) {
            bool result = true;
            try {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this.ip = ip;
                this.port = port;
                socket.Connect(new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(this.port)));
                thread = new Thread(StartReceive);
                thread.IsBackground = true;
                thread.Start();
            }
            catch (Exception) {
                result = false;
            }
            return result;
        }
        private void StartReceive(object obj) {
            string str;
            while (true) {
                Socket receiveSocket = obj as Socket;
                try {
                    int result = receiveSocket.Receive(buffer);
                    if (result == 0) {
                        break;
                    }
                    else {
                        str = Encoding.Default.GetString(buffer);
                    }
                }
                catch (Exception) {

                    throw;
                }
            }
        }
        public bool close() {
            bool result = true;
            try {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                thread.Abort();
                socket = null;
                thread = null;
                GC.Collect();
            }
            catch (Exception) {

                result = false;
            }
            return result;
        }
        public void send(string str) {
            socket.Send(Encoding.Default.GetBytes(str));
        }
        public void sendbytes(byte[] buffer) {
            socket.Send(buffer);
        }
        public bool isConnection() {
            bool blockingState = socket.Blocking;
            try {
                if (!socket.Connected) {
                    try {
                        close();
                        connect(this.ip, this.port);
                    }
                    catch (Exception) {

                        return false;
                    }
                }
                byte[] tmp = new byte[1];
                socket.Blocking = false;
                socket.Send(tmp, 0, 0);
                socket.Blocking = blockingState;
                return true;
            }
            catch (Exception) {

                return false;
            }
        }
    }
    class SocketServer
    {
        private static Dictionary<string, Socket> socketList = new Dictionary<string, Socket>();
        public SocketServer(string ip, string port) {
            try {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint IEP = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
                socket.Bind(IEP);
                socket.Listen(20);
                Thread thread = new Thread(new ParameterizedThreadStart(StartServer));
                thread.IsBackground = true;
                thread.Start(socket);
            }
            catch (Exception) {

                throw;
            }
        }
        public void StartServer(object obj) {
            string str;
            while (true) {
                Socket recevicesSocket = ((Socket)obj).Accept();
                str = recevicesSocket.RemoteEndPoint.ToString();
                socketList.Add(str, recevicesSocket);
                Thread thread = new Thread(startReceive);
                thread.IsBackground = true;
                thread.Start(recevicesSocket);
            }
        }
        public void startReceive(object obj) {
            while (true) {
                try {
                    byte[] buffer = new byte[2048];
                    int count = ((Socket)obj).Receive(buffer);
                    if (count == 0) break;
                    string str = Encoding.Default.GetString(buffer, 0, count);
                    string ip = ((Socket)obj).RemoteEndPoint.ToString();
                }
                catch (Exception) {

                    throw;
                }
            }
        }
        private void send2Client(string ip, string str) {
            byte[] bytes = new byte[2048];
            bytes = Encoding.Default.GetBytes(str);
            if (socketList.ContainsKey(ip)) {
                try {
                    socketList[ip].Send(bytes);
                }
                catch (Exception) {

                    throw;
                }
            }
        }
    }
    class TcpClient
    {
        Socket m_client;
        byte[] buffer = new byte[3072 * 2048];
        bool isOpen = false;
        bool hasClient = false;
        bool check_client() {
            try {
                if (m_client == null) return false;
                bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected;
                return isConnect;
            }
            catch (Exception) {

                return false;
            }
        }
        void AcceptCallBack(IAsyncResult ar) {
            try {
                if (check_client()) {
                    m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client);
                    hasClient = true;
                    while (hasClient) {
                        Thread.Sleep(500);
                        if (!check_client()) {
                            break;
                        }

                    }
                    hasClient = false;
                }
                if (isOpen) {
                    Open();
                }
            }
            catch (Exception) {

                throw;
            }
        }
        void ReceiveCallBack(IAsyncResult ar) {
            try {
                var client = ar.AsyncState as Socket;
                int length = client.EndReceive(ar);
                if (length>0) {
                    //执行文件传输方法
                    OnDataRecive?.Invoke(buffer.Take(length).ToArray());
                }
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client);
            }
            catch (Exception) {

                throw;
            }
        }
        public event Action<byte[]> OnDataRecive;
        string m_ip;
        int m_port;
        public void Open(string ip, int port) {
            Close();
            IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port);
            m_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_client.BeginConnect(serverip, AcceptCallBack, m_client);
            isOpen = true;
            m_ip = ip;
            m_port = port;
        }
        public void Open() {
            Open(m_ip, m_port);
        }
        public void Close() {
            if (m_client != null) {
                if (m_client.Connected)
                    m_client.Shutdown(SocketShutdown.Both);
                m_client.Close();
                m_client = null;
            }
            hasClient = false;
            isOpen = false;
        }
        public bool IsOpen() {
            return isOpen;
        }
        public bool IsConnected(){
            return hasClient;
        }
        public void Send(byte[] data) {
            if (hasClient) {
                m_client.Send(data);
            }
        }
        public void Send(string str) {
            if (hasClient) {
                m_client.Send(Encoding.Default.GetBytes(str));
            }
        }
    }
    class TcpServer
    {
        Socket m_server;
        Socket m_client;
        byte[] buffer = new byte[1024];
        bool isOpen = false;
        bool hasClient = false;
        bool check_client() {
            try {
                if (m_client == null)
                    return false;
                bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected;
                return isConnect;
            }
            catch (Exception) {

                return false;
            }
        }
        void AcceptCallBack(IAsyncResult ar) {
            try {
                var server = ar.AsyncState as Socket;
                var client = server.EndAccept(ar);
                m_client = client;
                m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client);
                hasClient = true;
                while (true) {
                    Thread.Sleep(100);
                    if (!check_client()) {
                        if (m_client.Connected) {
                            m_client.Shutdown(SocketShutdown.Both);
                        }
                        m_client.Close();
                        m_client = null;
                        break;
                    }
                }
                hasClient = false;
                if (m_server!=null) {
                    m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server);
                }
            }
            catch (Exception) {

                throw;
            }
        }
        void ReceiveCallBack(IAsyncResult ar) {
            try {
                var client = ar.AsyncState as Socket;
                int length = client.EndReceive(ar);
                OnDataReceive?.Invoke(buffer.Take(length).ToArray());
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new
 AsyncCallback(ReceiveCallBack), client);
            }
            catch (Exception) {

                throw;
            }
        }
        public event Action<byte[]> OnDataReceive;
        public void Open(string ip,int port) {
            Close();
            IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port);
            m_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_server.Bind(serverip);
            m_server.Listen(0);
            m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server);
            isOpen = true;
        }
        public void Close() {
            hasClient = false;
            isOpen = false;
            if (m_server!=null) {
                if (m_server.Connected) {
                    m_server.Shutdown(SocketShutdown.Both);
                }
                m_server.Close();
                m_server = null;
            }
            if (m_client!=null) {
                if (m_client.Connected) {
                    m_client.Shutdown(SocketShutdown.Both);
                }
                m_client.Close();
                m_client = null;
            }
        }
        public bool IsOpen() {
            return isOpen;
        }
        public bool IsConnected() {
            return hasClient;
        }
        public void Send(byte[] data) {
            if (hasClient) {
                m_client.Send(data);

            }
        }
    }
}

 

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;
namespace TcpIp{    public class SocketClient    {        byte[] buffer = new byte[2048];        Socket socket;        Thread thread;        string ip, port;        public bool connect(string ip, string port) {            bool result = true;            try {                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                this.ip = ip;                this.port = port;                socket.Connect(new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(this.port)));                thread = new Thread(StartReceive);                thread.IsBackground = true;                thread.Start();            }            catch (Exception) {                result = false;            }            return result;        }        private void StartReceive(object obj) {            string str;            while (true) {                Socket receiveSocket = obj as Socket;                try {                    int result = receiveSocket.Receive(buffer);                    if (result == 0) {                        break;                    }                    else {                        str = Encoding.Default.GetString(buffer);                    }                }                catch (Exception) {
                    throw;                }            }        }        public bool close() {            bool result = true;            try {                socket.Shutdown(SocketShutdown.Both);                socket.Close();                thread.Abort();                socket = null;                thread = null;                GC.Collect();            }            catch (Exception) {
                result = false;            }            return result;        }        public void send(string str) {            socket.Send(Encoding.Default.GetBytes(str));        }        public void sendbytes(byte[] buffer) {            socket.Send(buffer);        }        public bool isConnection() {            bool blockingState = socket.Blocking;            try {                if (!socket.Connected) {                    try {                        close();                        connect(this.ip, this.port);                    }                    catch (Exception) {
                        return false;                    }                }                byte[] tmp = new byte[1];                socket.Blocking = false;                socket.Send(tmp, 0, 0);                socket.Blocking = blockingState;                return true;            }            catch (Exception) {
                return false;            }        }    }    class SocketServer    {        private static Dictionary<string, Socket> socketList = new Dictionary<string, Socket>();        public SocketServer(string ip, string port) {            try {                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                IPEndPoint IEP = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));                socket.Bind(IEP);                socket.Listen(20);                Thread thread = new Thread(new ParameterizedThreadStart(StartServer));                thread.IsBackground = true;                thread.Start(socket);            }            catch (Exception) {
                throw;            }        }        public void StartServer(object obj) {            string str;            while (true) {                Socket recevicesSocket = ((Socket)obj).Accept();                str = recevicesSocket.RemoteEndPoint.ToString();                socketList.Add(str, recevicesSocket);                Thread thread = new Thread(startReceive);                thread.IsBackground = true;                thread.Start(recevicesSocket);            }        }        public void startReceive(object obj) {            while (true) {                try {                    byte[] buffer = new byte[2048];                    int count = ((Socket)obj).Receive(buffer);                    if (count == 0) break;                    string str = Encoding.Default.GetString(buffer, 0, count);                    string ip = ((Socket)obj).RemoteEndPoint.ToString();                }                catch (Exception) {
                    throw;                }            }        }        private void send2Client(string ip, string str) {            byte[] bytes = new byte[2048];            bytes = Encoding.Default.GetBytes(str);            if (socketList.ContainsKey(ip)) {                try {                    socketList[ip].Send(bytes);                }                catch (Exception) {
                    throw;                }            }        }    }    class TcpClient    {        Socket m_client;        byte[] buffer = new byte[3072 * 2048];        bool isOpen = false;        bool hasClient = false;        bool check_client() {            try {                if (m_client == null) return false;                bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected;                return isConnect;            }            catch (Exception) {
                return false;            }        }        void AcceptCallBack(IAsyncResult ar) {            try {                if (check_client()) {                    m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client);                    hasClient = true;                    while (hasClient) {                        Thread.Sleep(500);                        if (!check_client()) {                            break;                        }
                    }                    hasClient = false;                }                if (isOpen) {                    Open();                }            }            catch (Exception) {
                throw;            }        }        void ReceiveCallBack(IAsyncResult ar) {            try {                var client = ar.AsyncState as Socket;                int length = client.EndReceive(ar);                if (length>0) {                    //执行文件传输方法                    OnDataRecive?.Invoke(buffer.Take(length).ToArray());                }                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client);            }            catch (Exception) {
                throw;            }        }        public event Action<byte[]> OnDataRecive;        string m_ip;        int m_port;        public void Open(string ip, int port) {            Close();            IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port);            m_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            m_client.BeginConnect(serverip, AcceptCallBack, m_client);            isOpen = true;            m_ip = ip;            m_port = port;        }        public void Open() {            Open(m_ip, m_port);        }        public void Close() {            if (m_client != null) {                if (m_client.Connected)                    m_client.Shutdown(SocketShutdown.Both);                m_client.Close();                m_client = null;            }            hasClient = false;            isOpen = false;        }        public bool IsOpen() {            return isOpen;        }        public bool IsConnected(){            return hasClient;        }        public void Send(byte[] data) {            if (hasClient) {                m_client.Send(data);            }        }        public void Send(string str) {            if (hasClient) {                m_client.Send(Encoding.Default.GetBytes(str));            }        }    }    class TcpServer    {        Socket m_server;        Socket m_client;        byte[] buffer = new byte[1024];        bool isOpen = false;        bool hasClient = false;        bool check_client() {            try {                if (m_client == null)                    return false;                bool isConnect = !(m_client.Poll(1000, SelectMode.SelectRead) && m_client.Available == 0) && m_client.Connected;                return isConnect;            }            catch (Exception) {
                return false;            }        }        void AcceptCallBack(IAsyncResult ar) {            try {                var server = ar.AsyncState as Socket;                var client = server.EndAccept(ar);                m_client = client;                m_client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), m_client);                hasClient = true;                while (true) {                    Thread.Sleep(100);                    if (!check_client()) {                        if (m_client.Connected) {                            m_client.Shutdown(SocketShutdown.Both);                        }                        m_client.Close();                        m_client = null;                        break;                    }                }                hasClient = false;                if (m_server!=null) {                    m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server);                }            }            catch (Exception) {
                throw;            }        }        void ReceiveCallBack(IAsyncResult ar) {            try {                var client = ar.AsyncState as Socket;                int length = client.EndReceive(ar);                OnDataReceive?.Invoke(buffer.Take(length).ToArray());                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client);            }            catch (Exception) {
                throw;            }        }        public event Action<byte[]> OnDataReceive;        public void Open(string ip,int port) {            Close();            IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port);            m_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            m_server.Bind(serverip);            m_server.Listen(0);            m_server.BeginAccept(new AsyncCallback(AcceptCallBack), m_server);            isOpen = true;        }        public void Close() {            hasClient = false;            isOpen = false;            if (m_server!=null) {                if (m_server.Connected) {                    m_server.Shutdown(SocketShutdown.Both);                }                m_server.Close();                m_server = null;            }            if (m_client!=null) {                if (m_client.Connected) {                    m_client.Shutdown(SocketShutdown.Both);                }                m_client.Close();                m_client = null;            }        }        public bool IsOpen() {            return isOpen;        }        public bool IsConnected() {            return hasClient;        }        public void Send(byte[] data) {            if (hasClient) {                m_client.Send(data);
            }        }    }}

 

new tcpip

上一篇:Elasticsearch系列(1):安装与介绍


下一篇:RabbitMQ官方入门案例