C#窗体实例:基于Socket和Tcp协议的通信程序

和之前那个Socket实现控制台通信的思想和具体代码是差不多的,不过窗体和控制台程序还是有些不同,这次写一下窗体,以后再用基于TcpListener、TcpClient实现程序和基于

Scoket和Udp协议实现程序。

首先运行效果如下:


服务器:

C#窗体实例:基于Socket和Tcp协议的通信程序_第1张图片


客户端:

C#窗体实例:基于Socket和Tcp协议的通信程序_第2张图片


服务器代码:

控件的使用上很简单,只用了两个Button按钮,一个启动服务器,一个用于发送信息,richText用于显示聊天信息,textBox输入信息。

具体代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//添加下列引用
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace Sever
{
    public partial class Form1 : Form
    {
        delegate void SetTextCallBack(string text);
        TcpClient client;
        NetworkStream stream;
        private Thread th;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.ReadOnly = true;
            textBox1.Enabled = false;
            button2.Enabled = false;
        }

        private void SetText(string text)
        {
            richTextBox1.AppendText("客户端对服务端说:" + text + "\r\n");
        }

        private void Run()
        {
            string msg = string.Empty;
            if (client.Connected)
            {
                while (true)
                {
                    try
                    {
                        byte[] data = new byte[256];
                        Int32 bytes = stream.Read(data, 0, data.Length);
                        msg = Encoding.Unicode.GetString(data, 0, bytes);
                        this.Invoke(new SetTextCallBack(SetText), msg);
                    }
                    catch
                    {
                        break;
                        MessageBox.Show("客户端退出");

                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                TcpListener server = new TcpListener(ip, 5555);
                richTextBox1.Text = "启动服务器成功,等待客户链接...\r\n";
                button1.Enabled = false;
                server.Start();
                client = server.AcceptTcpClient();
                textBox1.Enabled = true;
                button2.Enabled = true;
                textBox1.Focus();
                stream = client.GetStream();
                th = new Thread(new ThreadStart(Run));
                th.Start();
            }
            catch
            {
                MessageBox.Show("启动服务器失败");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                Byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);
                stream.Write(data, 0, data.Length);
                richTextBox1.AppendText("服务器对客户端说:" + textBox1.Text + "\r\n");
                textBox1.Text = "";
                textBox1.Focus();
            }
            catch
            {
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                th.Abort();
                stream.Close();
                client.Close();
            }
            catch
            {
            }
        }
    }
}


客户端代码:

客户端控件使用上和服务器端是完全一样的,具体代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//添加下列引用
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Client
{
    public partial class Form1 : Form
    {

        delegate void SetTextCallBack(string text);
        TcpClient client;
        NetworkStream stream;
        private Thread th;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtMessage.ReadOnly = true;
            txtSend.Enabled = false;
            btnSend.Enabled = false;
        }

        private void SetText(string text)
        {
            txtMessage.AppendText("服务端对客户端说:" + text + "\r\n");
        }

        private void Run()
        {
            string msg = string.Empty;
            if (client.Connected)
            {
                while (true)
                {
                    try
                    {
                        byte[] data = new byte[256];
                        Int32 bytes = stream.Read(data, 0, data.Length);
                        msg = Encoding.Unicode.GetString(data, 0, bytes);
                        this.Invoke(new SetTextCallBack(SetText), msg);
                    }
                    catch
                    {
                        break;
                        MessageBox.Show("服务器退出");

                    }
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient("127.0.0.1", 5555);
                stream = client.GetStream();
                btnStart.Enabled = false;
                txtSend.Enabled = true;
                btnSend.Enabled = true;
                txtSend.Focus();
                txtMessage.Text = "链接服务器成功\r\n";
                th = new Thread(new ThreadStart(Run));
                th.Start();
            }
            catch
            {
                MessageBox.Show("链接失败");
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] data = Encoding.Unicode.GetBytes(txtSend.Text);
                stream.Write(data, 0, data.Length);
                txtMessage.AppendText("客户端对服务器说:" + txtSend.Text + "\r\n");
                txtSend.Text = "";
                txtSend.Focus();
            }
            catch
            {
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                th.Abort();
                stream.Close();
                client.Close();
            }
            catch
            { }
        }
    }
}




你可能感兴趣的:(C#)