C#TCPClient应用-一个简单的消息发送和接收

简介:

 

TcpSend窗口用于发送消息,另外写一个用于接收消息的应用程序,消息接受到以后,必须要关闭接收消息的窗口,才能在接收新的消息,不知道怎么能解决这个问题。

源代码:

发送消息的窗口代码

 

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


namespace TCPSocket
{
    public partial class FrmTcpSend : Form
    {
        public FrmTcpSend()
        {
            InitializeComponent();
        }

        private void buttonSendFile_Click(object sender, EventArgs e)
        {
           // TcpClient tcpClient = new TcpClient(textBoxHostName.Text, Int32.Parse(textBoxPort.Text));
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect(IPAddress.Parse(textBoxHostName.Text), Int32.Parse(textBoxPort.Text));

            NetworkStream ns = tcpClient.GetStream();

            FileStream fs = File.Open("..\\..\\FrmTcpSend.cs", FileMode.Open);

            int data = fs.ReadByte();

            while (data != -1)
            {
                ns.WriteByte((byte)data);
                data = fs.ReadByte();
            }

            fs.Close();
            ns.Close();
            tcpClient.Close();

        }

        private void buttonSendMessage_Click(object sender, EventArgs e)
        {
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect(IPAddress.Parse(textBoxHostName.Text), Int32.Parse(textBoxPort.Text));

            NetworkStream ns = tcpClient.GetStream();


            if (ns.CanWrite)
            {
                Byte[] sendBytes = Encoding.UTF8.GetBytes(textBoxMessage.Text);
                ns.Write(sendBytes, 0, sendBytes.Length);
            }
            else
            {
                MessageBox.Show("不能写入数据流", "终止", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                //Console.WriteLine("You cannot write data to this stream.");
                tcpClient.Close();

                // Closing the tcpClient instance does not close the network stream.
                ns.Close();
                return;
            }


            ns.Close();
            tcpClient.Close();

        }
    }
}

 

 

接收消息的窗口代码

 

 

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

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

            //Thread thread = new Thread(new ThreadStart(Listen));

            Thread thread = new Thread(new ThreadStart(SocketListen));

            thread.Start();

            IPAddress ipAddress = IPAddress.Any; //IPAddress.Parse("172.16.102.11");


            this.Text = ipAddress.ToString()+"正在监听...";

        }

        protected delegate void UpdateDisplayDelegate(string text);


        public void Listen()
        {
            IPAddress ipAddress = IPAddress.Any; //IPAddress.Parse("172.16.102.11");


           
            
            TcpListener tcpListener = new TcpListener(ipAddress,9999);
            tcpListener.Start();

            TcpClient tcpClient = tcpListener.AcceptTcpClient();

           
            NetworkStream ns = tcpClient.GetStream();

            StreamReader sr = new StreamReader(ns);

            string result = sr.ReadToEnd();

            Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });

            tcpClient.Close();
            tcpListener.Stop();
        }

        public void SocketListen()
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(new IPEndPoint(IPAddress.Any, 9999));

            listener.Listen(0);

            Socket socket = listener.Accept();
            Stream netStream = new NetworkStream(socket);
            StreamReader reader = new StreamReader(netStream);

            string result = reader.ReadToEnd();
            Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });

            socket.Close();
            listener.Close();


        }

        public void UpdateDisplay(string text)
        {
            richTextBox1.Text = text;
        }


    }
}

 

 


本文转自tiasys博客园博客,原文链接:http://www.cnblogs.com/tiasys/archive/2009/11/24/1609286.html,如需转载请自行联系原作者

相关文章
|
3月前
|
存储 安全 物联网
C# 在物联网 (IoT) 应用中的应用
本文介绍了C#在物联网(IoT)应用中的应用,涵盖基础概念、优势、常见问题及其解决方法。重点讨论了网络通信、数据处理和安全问题,并提供了相应的代码示例,旨在帮助开发者更好地利用C#进行IoT开发。
165 3
|
3月前
|
编译器 C#
c# - 运算符<<不能应用于long和long类型的操作数
在C#中,左移运算符的第二个操作数必须是 `int`类型,因此需要将 `long`类型的位移计数显式转换为 `int`类型。这种转换需要注意数据丢失和负值处理的问题。通过本文的详细说明和示例代码,相信可以帮助你在实际开发中正确使用左移运算符。
55 3
|
3月前
|
编译器 C#
c# - 运算符<<不能应用于long和long类型的操作数
在C#中,左移运算符的第二个操作数必须是 `int`类型,因此需要将 `long`类型的位移计数显式转换为 `int`类型。这种转换需要注意数据丢失和负值处理的问题。通过本文的详细说明和示例代码,相信可以帮助你在实际开发中正确使用左移运算符。
91 1
|
8月前
|
C#
C#||应用框体设计计算器
C#||应用框体设计计算器
|
3月前
|
编译器 C#
c# - 运算符<<不能应用于long和long类型的操作数
在C#中,左移运算符的第二个操作数必须是 `int`类型,因此需要将 `long`类型的位移计数显式转换为 `int`类型。这种转换需要注意数据丢失和负值处理的问题。通过本文的详细说明和示例代码,相信可以帮助你在实际开发中正确使用左移运算符。
34 0
|
5月前
|
设计模式 开发框架 前端开发
MVC 模式在 C# 中的应用
MVC(Model-View-Controller)模式是广泛应用于Web应用程序开发的设计模式,将应用分为模型(存储数据及逻辑)、视图(展示数据给用户)和控制器(处理用户输入并控制模型与视图交互)三部分,有助于管理复杂应用并提高代码可读性和维护性。在C#中,ASP.NET MVC框架常用于构建基于MVC模式的Web应用,通过定义模型、控制器和视图,实现结构清晰且易维护的应用程序。
85 2
|
5月前
|
编译器 C# Android开发
Uno Platform 是一个用于构建跨平台应用程序的强大框架,它允许开发者使用 C# 和 XAML 来创建适用于多个平台的应用
Uno Platform 是一个用于构建跨平台应用程序的强大框架,它允许开发者使用 C# 和 XAML 来创建适用于多个平台的应用
444 8
|
4月前
|
消息中间件 网络协议 安全
C# 一分钟浅谈:WebSocket 协议应用
【10月更文挑战第6天】在过去的一年中,我参与了一个基于 WebSocket 的实时通信系统项目,该项目不仅提升了工作效率,还改善了用户体验。本文将分享在 C# 中应用 WebSocket 协议的经验和心得,包括基础概念、C# 实现示例、常见问题及解决方案等内容,希望能为广大开发者提供参考。
264 0
|
5月前
|
存储 C# 开发者
枚举与结构体的应用:C#中的数据组织艺术
在C#编程中,枚举(`enum`)和结构体(`struct`)是非常重要的数据类型。枚举用于定义命名常量集合,提高代码可读性;结构体则封装相关数据字段,适合小型数据集。本文从基本概念入手,探讨它们的使用技巧、常见问题及解决方案,帮助开发者更好地利用这些特性构建健壮的应用程序。
74 8
|
4月前
|
Web App开发 网络协议 API
基于C#编写一个远程桌面应用
基于C#编写一个远程桌面应用
125 0