图文版网络聊天程序

1、服务器端


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;

namespace 服务器端
{
    public partial class Form1 : Form
    {
        private Socket socket;
        private Socket clientSocket;
        private Thread tAcceptMsg;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        private void AcceptMessage()
        {
            clientSocket = socket.Accept();
            this.labelState.Text = "与客户机" + clientSocket.RemoteEndPoint.ToString() + "成功建立连接。";
            while (true)
            {
                try
                {
                    NetworkStream nStream = new NetworkStream(clientSocket);
                    byte[] datasize = new byte[4];
                    nStream.Read(datasize, 0, 4);
                    int size = System.BitConverter.ToInt32(datasize, 0);
                    byte[] Message = new byte[size];
                    int dataleft = size;
                    int start = 0;
                    while (dataleft > 0)
                    {
                        int recv = nStream.Read(Message, start, dataleft);
                        start += recv;
                        dataleft -= recv;
                    }
                    this.richTextBoxReceive.Rtf = System.Text.Encoding.Unicode.GetString(Message);
                }
                catch
                {
                    this.labelState.Text = "与客户机断开连接。";
                    break;
                }
            }
        }
        
        private void buttonStatr_Click(object sender, EventArgs e)
        {
            this.buttonStatr.Enabled = false;
            IPAddress ip = IPAddress.Parse(this.textBoxIP.Text);
            IPEndPoint IPP = new IPEndPoint(ip, Int32.Parse(this.textBoxPort.Text));
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(IPP);
            socket.Listen(10);
            tAcceptMsg = new Thread(new ThreadStart(AcceptMessage));
            tAcceptMsg.Start();
        }

        private void richTextBoxSend_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                string str = this.richTextBoxSend.Rtf;
                int i = str.Length;
                if (i == 0) return;
                else i *= 2; //str为UniCode编码,每个字符占2B,实际字节数应*2
                byte[] datasize = new byte[4];
                //将32位整数值转换为字节数组
                datasize = System.BitConverter.GetBytes(i);
                byte[] sendbytes = System.Text.Encoding.Unicode.GetBytes(str);
                try
                {
                    NetworkStream netStream = new NetworkStream(clientSocket);
                    netStream.Write(datasize, 0, 4);
                    netStream.Write(sendbytes, 0, sendbytes.Length);
                    netStream.Flush();
                    this.richTextBoxSend.Rtf = "";
                }
                catch
                {
                    MessageBox.Show("信息无法发送!");
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                socket.Close();
                tAcceptMsg.Abort();
            }
            catch { }
        } 
    }
}


2、客户端

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;

namespace 客户端
{
    public partial class Form1 : Form
    {
        private Socket socket;
        private Thread tAcceptMsg;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        private void AcceptMessage()
        {
            while (true)
            {
                try
                {
                    NetworkStream nstream = new NetworkStream(socket);
                    byte[] datasize = new byte[4];
                    nstream.Read(datasize, 0, 4);
                    int size = System.BitConverter.ToInt32(datasize, 0);
                    byte[] message = new byte[size];
                    int dataleft = size,start=0;
                    while (dataleft > 0)
                    {
                        int recv = nstream.Read(message, start, dataleft);
                        start += recv;
                        dataleft -= recv;
                    }
                    this.richTextBoxReceive.Rtf = System.Text.Encoding.Unicode.GetString(message);
                }
                catch { }
            }
        }

        private void richTextBoxSend_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                string str = this.richTextBoxSend.Rtf;
                int i = str.Length;
                if (i == 0) return;
                else i *= 2;
                byte[] datasize = new byte[4];
                datasize = System.BitConverter.GetBytes(i);
                byte[] sendBytes = System.Text.Encoding.Unicode.GetBytes(str);
                try
                {
                    NetworkStream netStream = new NetworkStream(socket);
                    netStream.Write(datasize, 0, 4); //发送信息长度大小
                    netStream.Write(sendBytes, 0, sendBytes.Length);//发送信息
                    netStream.Flush();
                    this.richTextBoxSend.Rtf = "";
                }
                catch
                {
                    MessageBox.Show("信息无法发送!!");
                }
            }
        }

        private void buttonLink_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(this.textBoxIP.Text);
            IPEndPoint IPP = new IPEndPoint(ip, Int32.Parse(this.textBoxPort.Text));
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(IPP);
            }
            catch
            {
                MessageBox.Show("与服务器连接失败!");
                return;
            }
            this.labelState.Text = "与服务器" + this.textBoxIP.Text + ":" + this.textBoxPort.Text + "成功建立连接。";
            tAcceptMsg = new Thread(new ThreadStart(AcceptMessage));
            tAcceptMsg.IsBackground = true;
            tAcceptMsg.Start();
            this.buttonLink.Enabled = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                socket.Close();
                tAcceptMsg.Abort();
            }
            catch { }
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值