基于TCP网络通信程序设计

来源:互联网 发布:投影仪有网络连接 编辑:程序博客网 时间:2024/05/02 04:30

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.IO;using System.Net;using System.Net.Sockets;using System.Threading;namespace 服务器端{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private bool bConnected = false;        private Thread tAcceptMsg = null;        private IPEndPoint IPP = null;//用于Socket通信的IP地址和端口        private Socket socket = null;        private Socket clientSocket = null;        private NetworkStream nStream = null;//网络访问的基础数据流        private TextReader tReader = null;        private TextWriter wReader = null;        private void AcceptMessage()        {            clientSocket = socket.Accept();//一直等待连接            if (clientSocket != null)            {                bConnected = true;                this.label1.Text = "与客户" + clientSocket.RemoteEndPoint.ToString() + "成功建立连";            }            nStream = new NetworkStream(clientSocket);            tReader = new StreamReader(nStream);            wReader = new StreamWriter(nStream);            string sTemp;            while (bConnected)            {                try                {                    sTemp = tReader.ReadLine();                    if (sTemp.Length != 0)                    {                        lock (this)                        {                            richTextBoxReceive.Text = "客户机:" + sTemp + Environment.NewLine + richTextBoxReceive.Text;                        }                    }                }                catch                {                    tAcceptMsg.Abort();                    MessageBox.Show("无法与客户机进行通信。");                }            }            clientSocket.Shutdown(SocketShutdown.Both);            clientSocket.Close();            socket.Shutdown(SocketShutdown.Both);            socket.Close();        }        private void Form1_Load(object sender, EventArgs e)        {            this.label1.Text = "无客户机请求连接";        }        private void buttonStart_Click(object sender, EventArgs e)        {            //指定服务器端口,Any表示服务器侦听所有网络接口上的客户活动            IPP = new IPEndPoint(IPAddress.Any, 65535);            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            socket.Bind(IPP);            socket.Listen(0);//0表示连接数量不限            //创建侦听线程            tAcceptMsg = new Thread(new ThreadStart(this.AcceptMessage));            tAcceptMsg.Start();            buttonStart.Enabled = false;        }        private void richTextBoxSend_KeyPress(object sender, KeyPressEventArgs e)        {            if (e.KeyChar == (char)Keys.Enter)            {                if (bConnected)                {                    try                    {                        lock (this)                        {                            richTextBoxReceive.Text = "我:" + richTextBoxSend.Text + richTextBoxReceive.Text;                            //客户机聊天信息写入网络流,以便服务器接受                            wReader.WriteLine(richTextBoxSend.Text);                            wReader.Flush();                            richTextBoxSend.Text = "";                            richTextBoxSend.Focus();                        }                    }                    catch                    {                        MessageBox.Show("无法与客户机通信");                    }                }                else                {                    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.IO;using System.Net;using System.Net.Sockets;using System.Threading;namespace 客户端{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            CheckForIllegalCrossThreadCalls = false;//禁用此异常        }        public bool bconnected = false;        public Thread tAcceptMsg = null;        public IPEndPoint IPP = null;        public Socket socket = null;        public NetworkStream nStream = null;        public TextWriter wReader = null;        public TextReader tReader = null;        public void AcceptMessage()        {            string sTemp;            while (bconnected)            {                try                {                    sTemp = tReader.ReadLine();                    if (sTemp.Length != 0)                    {                        lock (this)                        {                            richTextBoxReceive.Text = "服务器:" + sTemp + Environment.NewLine + richTextBoxReceive.Text;                        }                    }                }                catch                {                    MessageBox.Show("无法与服务器通信。");                }            }            socket.Shutdown(SocketShutdown.Both);            socket.Close();        }        private void buttonLink_Click(object sender, EventArgs e)        {            if (textBoxIPAdress.Text == "") { MessageBox.Show("IP地址不能为空!!"); return; }            if (textBoxPort.Text == "") { MessageBox.Show("端口号不能为空!!"); return; }            try            {                IPP = new IPEndPoint(IPAddress.Parse(textBoxIPAdress.Text),                    int.Parse(textBoxPort.Text));                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,                    ProtocolType.Tcp);                socket.Connect(IPP);                if (socket.Connected)                {                    nStream = new NetworkStream(socket);                    tReader = new StreamReader(nStream);                    wReader = new StreamWriter(nStream);                    tAcceptMsg = new Thread(new ThreadStart(this.AcceptMessage));                    tAcceptMsg.Start();                    bconnected = true;                    buttonLink.Enabled = false;                    MessageBox.Show("与服务器成功建立连接,可以通信。");                }            }            catch            {                MessageBox.Show("无法与服务器通信。");            }        }        private void richTextBoxsend_KeyPress(object sender, KeyPressEventArgs e)        {            if (e.KeyChar ==(char)Keys.Enter)            {                if (bconnected)                {                    try                     {                        lock (this)                        {                            richTextBoxReceive.Text = "我:" + richTextBoxsend.Text + richTextBoxReceive.Text;                            wReader.WriteLine(richTextBoxsend.Text);                            wReader.Flush();                            richTextBoxsend.Text = "";                            richTextBoxsend.Focus();                        }                    }                    catch                    {                        MessageBox.Show("与服务器连接断开。");                    }                }                else                {                    MessageBox.Show("未与服务器建立连接,不能通信。");                }            }        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            try            {                socket.Close();                tAcceptMsg.Abort();            }            catch { }        }    }}


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 取票学生证没带怎么办 学生卡的失磁怎么办 学生证没有充磁买不了学生票怎么办 买学生票不在优惠区间怎么办 火车票学生优惠次数用完怎么办 学生乘火车优惠磁卡丢了怎么办 磁卡锁的卡丢了怎么办 电梯磁卡扣丢了怎么办 买火车票手机号填错了怎么办 买火车票乘客身份核验失败怎么办 火车票不在一个车厢怎么办站票 坐火车丢东西了怎么办 g2坐过站了怎么办 坐火车买近了怎么办 打印的纸质火车票丢失怎么办 格力空调没保修单怎么办 格力空调不兑现保修怎么办 哈空调如果退市怎么办 空调保修单丢了怎么办 海尔空调发票丢了怎么办 格力空调发票丢了怎么办 联程航班第一程延误怎么办 飞机经停10小时怎么办 去车站买票没带身份证怎么办 转机航班第一班延误了怎么办 转机航班第一班取消了怎么办 香港转机大陆行李托运怎么办 联程车票第一班车晚点怎么办 到了普吉机场接机怎么办 被骚扰电话打个不停怎么办 网贷不停发信息怎么办 网贷天天发信息怎么办 诈骗电话一直打个不停怎么办 寄快递电话号码写错了怎么办 寄快递收件人号码错了怎么办 嫒和媛分不清楚怎么办 快递柜单号没了怎么办 邮政蜜蜂箱 退件怎么办 手机狂收验证码怎么办 快递柜超过24小时怎么办 快递柜短信删了怎么办