Socket Client & Server

客户端例子代码

 Socket tcpSynClient;
        private byte[] tcpSynClBuffer = new byte[2048];


        public bool connect(string ip = "192.168.3.10", int port = 4999)
        {

            try
            {
                //一个已经存在的socket连接,重新new,再connect,发送数据时会出现您的主机中的软件中止了一个已建立的连接; 
                //但如果没有重新new,不能再connect
                tcpSynClient = new Socket(IPAddress.Parse(ip).AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                tcpSynClient.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
                Console.WriteLine("连接服务器成功");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("连接服务器失败");
                Console.WriteLine(ex.Message);
                throw ex;
                return false;
            }
        }
        public void disconnect()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (tcpSynClient != null)
            {
                if (tcpSynClient.Connected)
                {
                    try { tcpSynClient.Shutdown(SocketShutdown.Both); }
                    catch { }
                    tcpSynClient.Close();
                }
                tcpSynClient = null;
            }
        }
        private byte[] WriteSyncData(byte[] write_data)
        {
            byte[] data;
            if (tcpSynClient.Connected)
            {
                try
                {
                    tcpSynClient.Send(write_data, 0, write_data.Length, SocketFlags.None);
                    int result = tcpSynClient.Receive(tcpSynClBuffer, 0, tcpSynClBuffer.Length, SocketFlags.None);


                    data = new byte[result];
                    // 返回结果result:    收到的字节数。
                    if (result == 0)
                    {

                        return data;
                    }


                    // Read response data
                    {
                        Array.Copy(tcpSynClBuffer, 0, data, 0, result);
                    }
                    return data;
                }
                catch (SystemException ex)
                {
                    data = new byte[0];
                    return data;
                }
            }
            else
                return null;
        }

服务器端例子代码

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;
using System.Windows.Forms;

namespace ServerExample
{
    public class TCPEventArgs : EventArgs // 事件参数类
    {

        public string ClientIP {get;set;}
        public string RecvMsg { get; set; }
    }
    // 声明委托
    public delegate void TCPEventHandler(object sender, TCPEventArgs e);

    public class MyListener
    {
        private TcpListener server = null;
        private TcpClient client = null;
        private Thread LoadThread = null;
        private NetworkStream stream = null;
        CancellationTokenSource _cancelSource = new CancellationTokenSource();
        public event TCPEventHandler OnRecvMsg;  //定义事件
        ManualResetEvent _resetEvent = new ManualResetEvent(true);

        public void Close()
        {
            
            //_cancelSource.Cancel();
            if(stream!=null)
                stream.Close();
            if(client!=null)
                client.Close();

            server.Stop();
            if(LoadThread!=null)
                LoadThread.Abort();

  
            Console.WriteLine("Close Server!");
        }
        private void Start()
        {
            try
            {
                // Set the TcpListener on port 3000.
                Int32 port = 3000;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {

            }
        }
        private void Listen()
        {

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            try
            {
                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also use server.AcceptSocket() here.

                    client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");



                    data = null;

                    // Get a stream object for reading and writing
                    if (client.Connected)
                        stream = client.GetStream();
                    else
                        return;

                    int i;

                    // Loop to receive all the data sent by the client.
                    while (stream.CanRead && (i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);

                        //=================触发事件=========================
                        TCPEventArgs e = new TCPEventArgs() {  ClientIP=client.Client.RemoteEndPoint.ToString(), RecvMsg= data};                        
                        OnRecvMsg(this,e);

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine("Sent: {0}", data);

                    }

                    // Shutdown and end connection
                    client.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }
            finally
            {
                server.Stop();
            }
        }
        public void Open()
        {
            Start();
            LoadThread = new Thread(Listen);//创建一个新的进程,以防界面卡死
            LoadThread.Start();




        }
    }
}
原文地址:https://www.cnblogs.com/zitjubiz/p/net_socket_client_server_Code.html