c# socket通讯实现简单的窗口信息互相发送 (聊天室的deom)

2 篇文章 0 订阅

这次使用socket来实现简单的窗口信息互相发送 

首先我们创建一个服务器端 services (winfrom文件)

这边注意。你的ip地址和端口号可以  命令建+r  打开cmd  输入ipconfig找到自己的ip地址 每个人的ip地址都不一样

代码部分

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.Sockets;
using System.Net;

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


        IPAddress ip;
        TcpListener listener;
  
        TcpClient tcpClient = new TcpClient();
      


        private void button2_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.RunWorkerAsync();//开始进行 但是是在线程里run控件  会报错
            Control.CheckForIllegalCrossThreadCalls = false; //直接不检查这个错误  前后台同时运行
        }


        private void textBoxIp_TextChanged(object sender, EventArgs e)
        {

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            IPAddress ip = IPAddress.Parse(this.textBoxIp.Text);//创建ip
            TcpListener listener = new TcpListener(ip, Convert.ToInt32(this.textBoxPort.Text));//创建tcp监听对象
            listener.Start();


            this.textBoxInfo.Text = "服务器启动-" + DateTime.Now.ToShortTimeString() + "\r\n" +
                this.textBoxInfo.Text;


            TcpClient tcpClient = listener.AcceptTcpClient();//中断 等待  我们使用多线程 fuck妈的
            this.textBoxInfo.Text = "连接成功-" + DateTime.Now.ToShortTimeString() + "\r\n" +
                this.textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();//创建管道 储存信息
            byte[] byteArrary = new byte[1024];//因为不知道多大 所以大一点 

            try
            {

                while (true)//创建死循环  不影响
                {
                    int length = stream.Read(byteArrary, 0, 1024);//会把这个流里面的字节数组放到bytearray里面 返回来一个长度  中断了这个。中断 等待  我们使用多线程 fuck妈的
                    //length其实就是客户端发送的字节数组长度  
                    string receiveMessage = Encoding.Unicode.GetString(byteArrary, 0, length);
                    this.textBoxInfo.Text = "接受到的:" + receiveMessage + "-" + DateTime.Now.ToShortTimeString() + "\r\n" +
                      this.textBoxInfo.Text;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("mistake");
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {

            
            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "发送" + message + DateTime.Now.ToShortTimeString() + "\r\n" +
             this.textBoxInfo.Text;

            NetworkStream stream  = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray, 0, byteArray.Length);// 发送字节流  字节串的字节数组
        }

        private void textBoxInfo_TextChanged(object sender, EventArgs e)
        {

        }

        

        
        }
    }
   切记先创建winform窗口,控件拖完了再去看代码,不要直接复制黏贴,winfrom不会识别你的代码中的控件名字,这个要记住。 

 

客户端

 

这部分我还没有写具体的添加用户function,所以你们在拖控件时候 不要把这个“添加用户”拖进去 。

代码部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
 
using System.Net.Sockets;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;

namespace Clientform
{
    public partial class Form1 : Form
    {

        TcpClient tcpClient = new TcpClient();
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {

            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "发送" + message + DateTime.Now.ToShortTimeString() + "\r\n" +
             this.textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);//存在数组里面
            stream.Write(byteArray, 0, byteArray.Length);// 发送字节流  字节串的字节数组
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();

            try
            {
                tcpClient.Connect(this.textBoxIp.Text, Convert.ToInt32(this.textBoxPort.Text));
                this.textBoxInfo.Text = "连接成功 " + DateTime.Now.ToShortTimeString() + "\r\n" +
                    this.textBoxInfo.Text;
                this.backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {

                MessageBox.Show("连接失败" + ex.Message);
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)//写接收的代码
        {
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArrary = new byte[1024];//因为不知道多大 所以大一点 

            try
            {

                while (true)//创建死循环  不影响
                {
                    int length = stream.Read(byteArrary, 0, 1024);//会把这个流里面的字节数组放到bytearray里面 返回来一个长度  中断了这个。中断 等待  我们使用多线程 fuck妈的 但是多线程我还没写 只用了backgroundworker  这个你们最好自己改了
                    //length其实就是客户端发送的字节数组长度  
                    string receiveMessage = Encoding.Unicode.GetString(byteArrary, 0, length);//这边转码  utf8格式也可以
                    this.textBoxInfo.Text = "接受到的:" + receiveMessage + "-" + DateTime.Now.ToShortTimeString() + "\r\n" +
                      this.textBoxInfo.Text;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("mistake");
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form1 addnew = new Form1();

            addnew.Show();
        }

        private void textBoxInfo_TextChanged(object sender, EventArgs e)
        {

        }

    }

}

注意事项是整个程序我没有写多线程,用backgroundworker代替了多线程,自己修改。简单的demo实现,但是只能客户端发服务器,后续功能自己添加。

特别注意,不要直接黏贴复制! 看代码再拖控件,搞清楚控件的name再去黏贴复制代码!别贪方便。

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

董厂长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值