C# Socket 编程

Server端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace SocketCommunication
{
    public partial class Server : Form
    {
        public Server()
        {
            InitializeComponent();
        }
        public Socket communicationSocket { get; set; }
        public Dictionary<string, Socket> dClient { get; set; }
        private void btn_listen_Click(object sender, EventArgs e)
        {
            Socket socketServer = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //create server socket
            //IPAddress iP = new IPAddress(Encoding.UTF8.GetBytes(txt_IP.Text)); //set ip address
            IPAddress iP = IPAddress.Any;
            IPEndPoint iPEndPoint = new IPEndPoint(iP, int.Parse(txt_port.Text)); //set ip address and port number
            socketServer.Bind(iPEndPoint);   //server socket bind endpoint
            socketServer.Listen(10);   //start listening
            showMsg("Begin listening...");
            dClient = new Dictionary<string, Socket>();
            Thread th = new Thread(new ParameterizedThreadStart(listen));
            th.IsBackground = true;
            th.Start(socketServer);
        }
        public void listen(Object o)
        {
            Socket socketServer = (Socket)o;
            while(true)
            {
                try
                {
                    //socketServer.BeginAccept(new AsyncCallback());
                    communicationSocket = socketServer.Accept();  
                    showMsg(communicationSocket.RemoteEndPoint.ToString() + " ");
                    dClient.Add(communicationSocket.RemoteEndPoint.ToString(), communicationSocket);
                    Socket_Combo.Items.Add(communicationSocket.RemoteEndPoint.ToString());
                    Thread th = new Thread(receive);
                    th.IsBackground = true;
                    th.Start(communicationSocket);               
                }
                catch
                {

                }
                

            }
            
        }
        public void receive(object o)
        {
            Socket receiveSocket = o as Socket;
            
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int re = receiveSocket.Receive(buffer);
                    if (re == 0)
                        break;
                    string str = Encoding.UTF8.GetString(buffer, 0, re);

                    showMsg(receiveSocket.RemoteEndPoint.ToString() + ":" + str);

                }
                catch
                {

                }
                
            }
        }

        public void showMsg(string str)
        {
            richTextBox1.AppendText(str + "\r\n");
        }
        private void txt_IP_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
           Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Btn_Send_Click(object sender, EventArgs e)
        {
            List<byte> strList = new List<byte>();
            strList.Add(0);
            string Msg = txt_Msg.Text;
            byte[] buffer = Encoding.UTF8.GetBytes(Msg);
            strList.AddRange(buffer);
            byte[] newBuffer = strList.ToArray<byte>();
            dClient[Socket_Combo.SelectedItem.ToString()].Send(newBuffer);
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"D:\test";
            ofd.Title = "Please select file to send...";
            ofd.Filter = "All files|*.*";

            ofd.ShowDialog();
            text_Path.Text = ofd.FileName;
        }

        private void btn_SendFile_Click(object sender, EventArgs e)
        {
            string path = text_Path.Text;
            using (FileStream fsRead = new FileStream(path,FileMode.Open, FileAccess.Read))
            {
                List<byte> fileList = new List<byte>();
                fileList.Add(1);
                byte[] buffer = new byte[1024*1024*5];
                int r = fsRead.Read(buffer,0, buffer.Length);
                fileList.AddRange(buffer);
                byte[] newbuffer = fileList.ToArray<byte>();
                dClient[Socket_Combo.SelectedItem.ToString()].Send(newbuffer, r+1, SocketFlags.None);

            }
        }

        private void btn_vibration_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;
            dClient[Socket_Combo.SelectedItem.ToString()].Send(buffer);
        }
    }
}

 


Client1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace Client1
{
    public partial class Client1 : Form
    {
        public Client1()
        {
            InitializeComponent();
        }
        public Socket socketClient1 { get; set; }
        private void btn_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                socketClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //create Client socket
                                                                                                             //byte[] ipByte = Encoding.UTF8.GetBytes(txt_IP.Text);
                IPAddress iPAddress = IPAddress.Parse(txt_IP.Text);  //Parse ip address
                IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, int.Parse(txt_Port.Text));  //set endpoint

                socketClient1.Connect(iPEndPoint); //connect server
                ShowMsg("Connect successful...");
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start(socketClient1);
                //socketClient1.Send();
            }
            catch
            {

            }


        }
        public void ShowMsg(string str)
        {
            richTextBox1.AppendText(str+"\r\n");
        }
        public void Receive(object o)
        {
            try
            {
                Socket receiveSocket = o as Socket;
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = receiveSocket.Receive(buffer);
                    if (r == 0)
                        break;
                    if (buffer[0] == 0)
                    {                      
                        string sRcvMsg = Encoding.UTF8.GetString(buffer, 1, r-1);
                        ShowMsg(receiveSocket.RemoteEndPoint.ToString() + ":" + sRcvMsg);
                    }
                    else if(buffer[0] == 1)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.InitialDirectory = @"D:\test";
                        sfd.Filter = "All files|*.*";
                        sfd.ShowDialog(this);
                        string path = sfd.FileName;
                        using (FileStream fs = new FileStream(path,FileMode.Create,FileAccess.Write))
                        {
                            fs.WriteAsync(buffer, 1, r-1);
                        }
                        ShowMsg(receiveSocket.RemoteEndPoint.ToString() + ": send file");
                        MessageBox.Show("Successful Save");
                    }
                    else if(buffer[0] == 2)
                    {
                        shake();
                    }

                  
                }
            }
            catch
            {

            }
            
        }
        private void btn_Send_Click(object sender, EventArgs e)
        {
            try
            {
                string sSendRec = txt_Msg.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(sSendRec);
                socketClient1.Send(buffer);
            }
            catch
            {

            }


        }

        private void txt_Msg_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            this.Location = new Point(200, 200);
        }
        public void  shake()
        {
            for(int i=0;i<500; i++)
            {
                this.Location = new Point(200,200);
                this.Location = new Point(230,230);
                this.Location = new Point(200, 200);
            }
        }
    }
}
 

Client2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;


namespace Client2
{
    public partial class Client2 : Form
    {
        public Client2()
        {
            InitializeComponent();
        }

        public Socket socketClient1 { get; set; }
        private void btn_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                socketClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //create Client socket
                                                                                                             //byte[] ipByte = Encoding.UTF8.GetBytes(txt_IP.Text);
                IPAddress iPAddress = IPAddress.Parse(txt_IP.Text);  //Parse ip address
                IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, int.Parse(txt_Port.Text));  //set endpoint

                socketClient1.Connect(iPEndPoint); //connect server
                ShowMsg("Connect successful...");
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start(socketClient1);
                //socketClient1.Send();
            }
            catch
            {

            }


        }
        public void ShowMsg(string str)
        {
            richTextBox1.AppendText(str + "\r\n");
        }
        public void Receive(object o)
        {
            try
            {
                Socket receiveSocket = o as Socket;
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = receiveSocket.Receive(buffer);
                    if (r == 0)
                        break;
                    if (buffer[0] == 0)
                    {
                        string sRcvMsg = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        ShowMsg(receiveSocket.RemoteEndPoint.ToString() + ":" + sRcvMsg);
                    }
                    else if (buffer[0] == 1)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.InitialDirectory = @"D:\test";
                        sfd.Filter = "All files|*.*";
                        sfd.ShowDialog(this);
                        string path = sfd.FileName;
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                        {
                            fs.Write(buffer, 1, r - 1);
                        }
                        ShowMsg(receiveSocket.RemoteEndPoint.ToString() + ": send file");
                        MessageBox.Show("Successful Save");
                    }
                    else if (buffer[0] == 2)
                    {
                        shake();
                    }

                }
            }
            catch
            {

            }
        }
       

        private void txt_Msg_TextChanged(object sender, EventArgs e)
        {

        }

       

        private void btn_Send_Click_1(object sender, EventArgs e)
        {
            try
            {
                string sSendRec = txt_Msg.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(sSendRec);
                socketClient1.Send(buffer);
            }
            catch
            {

            }

        }

        private void Client2_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            this.Location = new Point(200, 200);
        }
        public void shake()
        {
            for (int i = 0; i < 500; i++)
            {
                this.Location = new Point(200, 200);
                this.Location = new Point(230, 230);
                this.Location = new Point(200, 200);
            }
        }
    }
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值