【C#】基于TCP的简单通信系统

Console套接字版本

服务器端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ConsoleServer
{
    class Program
    {
        private static byte[] result = new Byte[1024];       //读写缓冲区
        private static int myprot = 8848;       //端口号
        private static Socket serverSocket;       //服务器端
        private static string sendMessage = "这是一条由服务器发送过来的消息,您好!";
        private static Socket clientsocket;//客户端
        static void Main(string[] args)
        {
            //1.初始化
            IPAddress ip =IPAddress.Parse("127.0.0.1");
            Console.WriteLine("初始化中。。。");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myprot));//绑定ip和端口号
            //2.开始监听
            serverSocket.Listen(10);
            Console.WriteLine("启动监听{0}成功,等待客户端接入", serverSocket.LocalEndPoint.ToString());
            //3.发送数据
            clientsocket = serverSocket.Accept();//阻塞线程
            clientsocket.Send(Encoding.Unicode.GetBytes(sendMessage));
            Console.WriteLine("向客户端发送消息:{0}", sendMessage);
            //4.接收数据
            int number = clientsocket.Receive(result);
            Console.WriteLine("接收客户端{0}消息{1}", clientsocket.RemoteEndPoint.ToString(),
                Encoding.Unicode.GetString(result, 0, number));
            //5.关闭连接
            clientsocket.Shutdown(SocketShutdown.Both);
            clientsocket.Close();
          
        }
    }
}

运行截图

客户端

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleClient
{
    class Program
    {
        private static byte[] result = new Byte[1024];
        private static Socket clientSocket;
        private static String sendMessage = "你好,这是来自客户端的回应";
        private static int port = 8848;
     
        static void Main(string[] args)
        {
            //1.初始化
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.WriteLine("初始化成功,正在连接服务器");
            //2.连接服务器
            try
            {
                clientSocket.Connect(ip, port);
                Console.WriteLine("连接成功!");
            }
            catch
            {
                Console.WriteLine("连接服务器失败");
                return;
            }
            //3.接收服务器发过来的数据
            int receiveLength = clientSocket.Receive(result);
            Console.WriteLine("接收服务器消息:{0}", Encoding.Unicode.GetString(result, 0, receiveLength));
            //4.向服务器发送数据
            clientSocket.Send(Encoding.Unicode.GetBytes(sendMessage));
            Console.WriteLine("向服务器发送消息:{0}", sendMessage);
            //5.关闭连接
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
           
        }
    }
}

运行截图

WinForm TCP类版本

界面设计

其实也没有啥好设计的,主要是要显示你的所有操作

服务器:

客户端

编码实现

服务器

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

namespace SocketServer
{

    public partial class Form1 : Form
    {
        private IPAddress localAddress;
        private const int port = 8848;
        private TcpListener tcpListener;
        private TcpClient tcpClient;
        private NetworkStream networkStream;
        private BinaryReader br;
        private BinaryWriter bw;
        private String log = "";
        private String receive_message = "";

        public Form1()
        {
            InitializeComponent();
            localAddress = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
            tv_server_status.Text = "准备就绪,IP: "+localAddress;
            log = log + getTime() + "程序启动,准备监听";
            tb_log.Text = log;
            tb_log.ScrollToCaret();
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btn_start_server_Click(object sender, EventArgs e)
        {
            log = log + getTime() + "开始连接" + "\r\n";
            tcpListener = new TcpListener(localAddress, port);
            tcpListener.Start();
            log = log + getTime() + "IP:" + localAddress + " 端口号:" + port + " 已启用监听" + "\r\n";
            tcpClient = tcpListener.AcceptTcpClient();
            tv_server_status.Text = "已连接!";
            networkStream = tcpClient.GetStream();
            br = new BinaryReader(networkStream);
            bw = new BinaryWriter(networkStream);
            log = log + getTime() + "已连接客户端";
            tb_log.Text = log; 
            tb_log.ScrollToCaret();
        }

        private void btn_stop_server_Click(object sender, EventArgs e)
        {
            if (bw != null)
            {
                bw.Close();
            }
            if (br != null)
            {
                br.Close();
            }
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            if (tcpListener != null)
            {
                tcpListener.Stop();
            }
            tv_server_status.Text = "准备就绪";
            log = log + getTime() + "已停止";
            tb_log.Text = log;
            tb_log.ScrollToCaret();
        }
        private String getTime()
        {
            return "\r\n"+DateTime.Now.ToString()+ "\r\n";
        }

        private void btn_send_message_Click(object sender, EventArgs e)
        {
            if (tb_send_message.Text == null || tb_send_message.Text.Equals(""))
            {
                MessageBox.Show("发送信息不允许为空!");
            }
            else
            {
                String message = tb_send_message.Text;
                log = log + getTime() + "服务器发送信息:" + message;
                tb_log.Text = log;
                tb_log.ScrollToCaret();
                //发送信息
                bw.Write(message);
                bw.Flush();
                tb_send_message.Text = "";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String temp = br.ReadString();
            receive_message = receive_message+getTime() + temp;
            tb_receive_message.Text = receive_message;
            log = log + getTime() + "收到信息:" + temp;
            tb_receive_message.ScrollToCaret();
            tb_log.Text = log;
            tb_log.ScrollToCaret();
        }

        private void tb_receive_message_TextChanged(object sender, EventArgs e)
        {

        }

        private void tb_send_message_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

客户端

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

namespace SocketClient
{
    public partial class Form1 : Form
    {
        String log = "";
        private IPAddress localAddress;
        private const int port = 8848;
        private TcpListener tcpListener;
        private TcpClient tcpClient;
        private NetworkStream networkStream;
        private BinaryReader br;
        private BinaryWriter bw;
        public Form1()
        {
            InitializeComponent();
            log = log + getTime() + "准备就绪,请输入IP后点击开始按钮";
            tb_log.Text = log;
            tb_log.ScrollToCaret();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if (tb_send_message.Text == null || tb_send_message.Text.Equals(""))
            {
                MessageBox.Show("发送信息不能为空");
            }
            else
            {
                bw.Write(tb_send_message.Text);
                bw.Flush();
                log = log + getTime() + "发送信息:" + tb_send_message.Text;
                tb_send_message.Text = "";
                tb_log.Text = log;
                tb_log.ScrollToCaret();
            }
           
        }
        private String getTime()
        {
            return "\r\n"+DateTime.Now.ToString() + "\r\n";
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            if(tb_goal_ip.Text==null|| tb_goal_ip.Text.Equals(""))
            {
                MessageBox.Show("用户名或者密码不能为空");
            }
            else
            {
                log = log + getTime() + "正在向服务器发送连接请求,请稍后...";
                tb_log.Text = log;
                tb_log.ScrollToCaret();
                IPHostEntry remoteHost = Dns.GetHostEntry(tb_goal_ip.Text);
                tcpClient = new TcpClient();
                tcpClient.Connect(remoteHost.HostName, port);    //非同步
                if (tcpClient != null)
                {
                    log = log + getTime() + "连接成功!";
                    tb_log.Text = log;
                    networkStream = tcpClient.GetStream();
                    br = new BinaryReader(networkStream);
                    bw = new BinaryWriter(networkStream);
                }
            }
           
        }

        private void tb_goal_ip_TextChanged(object sender, EventArgs e)
        {

        }

        private void btn_receive_Click(object sender, EventArgs e)
        {
            log = log + getTime() + "接收信息中...";
            tb_log.Text = log;
            string rcvMsgStr = br.ReadString();
            log = log + getTime() + "接收到信息:" + rcvMsgStr;
            tb_log.Text = log;
            tb_log.ScrollToCaret();
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            if (bw != null)
            {
                bw.Close();
            }
            if (br != null)
            {
                br.Close();
            }
            if (tcpListener != null)
            {
                tcpListener.Stop();
            }
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            log = log + getTime() + "已断开与服务器连接";
            log = log + getTime() + "准备就绪,请输入IP后点击开始按钮";
            tb_log.Text = log;
            tb_log.ScrollToCaret();
        }
    }
}

运行截图

学习初期,可能编码实现或者逻辑有些不足,欢迎指正!

posted @ 2020-03-11 17:20  巴塞罗那的余晖  阅读(496)  评论(0编辑  收藏  举报
//雪花飘落效果