(转)winform下TCP通信的简单应用

本文转载自:http://blog.csdn.net/wanlong360599336/article/details/7557064

先看效果图:

TCP比较繁琐的就是三次握手定理,每次再发送数据前都要先建立连接确认。

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

namespace TCP
{
    public partial class Form1 : Form
    {
        public Form1()
        {  

            InitializeComponent();
        }
        //启动服务端
        TcpListener listener;
        delegate void SetTextCallBack(string text);
        private void button1_Click(object sender, EventArgs e)
        {
            //try
            //{
                label2.Text = "服务端已开启..";
                button1.Enabled = false;
                listener = new TcpListener(IPAddress.Any, 3000);
                listener.Start();
                Thread th = new Thread(new ThreadStart(ReceiveMsg));
                th.Start();
                th.IsBackground = true;
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}  

        }  

        public void ReceiveMsg()
        {  

            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                byte[] buffer = new byte[9899];
                NetworkStream stream = client.GetStream();
                int len = stream.Read(buffer, 0, buffer.Length);
                string msg = Encoding.Unicode.GetString(buffer, 0, len);
                SetText(msg);  

                stream.Flush();
                stream.Close();
                client.Close();  

            }  

        }
        public void SetText(string text)
        {
            try
            {
                if (this.richTextBox1.InvokeRequired)
                {
                    SetTextCallBack d = new SetTextCallBack(SetText);
                    this.Invoke(d, new object[] { text });
                }
                else
                {  

                    this.richTextBox1.Text += DateTime.Now.ToString() + "\n" + text + "\n";
                }  

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }  

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //FileStream fs = new FileStream(textBox2.Text,FileMode.OpenOrCreate,FileAccess.Read);
                //byte[] buff=new byte[fs.Length];
                //int rea = fs.Read(buff,0,buff.Length);
                string ip = textBox1.Text;
                string msg = richTextBox2.Text;
                //msg = string.Format("{0}:{1}:{2}:{3}:{4}:{5}",1,DateTime.Now.Ticks,"007","www","32",msg);
                TcpClient client = new TcpClient();
                client.Connect(IPAddress.Parse(ip), 3000);
                NetworkStream stream = client.GetStream();
                byte[] buffer = Encoding.Unicode.GetBytes(msg);
                stream.Write(buffer, 0, buffer.Length);
                //stream.Write(buff,0,rea);
                //label6.Text = "文件发送成功!";
                MessageBox.Show("发送成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务端未开启!");
            }
        }  

        private void button2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.button2_Click(sender,e);
            }
        }
        //存放的目录
       // private void button4_Click(object sender, EventArgs e)
       // {
        //    FolderBrowserDialog fbd = new FolderBrowserDialog();
        //    if(fbd.ShowDialog()==DialogResult.OK)
        //    {
         //       textBox3.Text = fbd.SelectedPath;
          //  }
       // }
        //发送的文件
       /// private void button3_Click(object sender, EventArgs e)
       //{
       //     OpenFileDialog ofd = new OpenFileDialog();
       //     if(ofd.ShowDialog()==DialogResult.OK)
       //     {
       //         textBox2.Text = ofd.FileName;
       //     }
       // }
       //文件发送
        //private void button5_Click(object sender, EventArgs e)
        //{
        //    FileStream fs = new FileStream(textBox2.Text,FileMode.Open,FileAccess.Read);
        //    byte[] buffer = new byte[fs.Length];
        //    int rea=fs.Read(buffer,0,buffer.Length);
        //    TcpClient client = new TcpClient();
        //    string ip = textBox1.Text;
        //    client.Connect(IPAddress.Parse(ip),3000);
        //    NetworkStream ns = client.GetStream();
        //    ns.Write(buffer,0,rea);
        //    MessageBox.Show("文件发送成功!");
        //    fs.Flush();
        //    ns.Flush();
        //    fs.Close();
        //    ns.Close();
        //}    }
}  

(转)winform下TCP通信的简单应用

时间: 2024-08-28 08:34:10

(转)winform下TCP通信的简单应用的相关文章

(转)winform下UPD通信的简单应用

本文转载自:http://blog.csdn.net/wanlong360599336/article/details/7557046 先看效果图: 使用UDP的好处就是不需要三次握手,但是缺点就是存在安全隐患. QQ就是利用UDP来传输数据的. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using Sy

linux下TCP/IP实现简单聊天程序

可以在同一台电脑上运行,在一个终端上运行服务器端,在一个终端上运行客户端. 服务器端的IP地址要和本地的IP相同,并分配端口号,客户端的默认设置为本地,端口号自动分配. 服务器端: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #in

基于TCP协议的简单Socket通信笔记(JAVA)

好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些网络编程的基础,这里就不提了,只记录最简单易懂实用的东西. 1.首先先来看下基于TCP协议Socket服务端和客户端的通信模型: Socket通信步骤:(简单分为4步) 1.建立服务端ServerSocket和客户端Socket 2.打开连接到Socket的输出输入流 3.按照协议进行读写操作 4.关闭相对应的资源 2.相关联的API: 1.首先先来看下S

Socket简单学习之Tcp通信

Socket网络通信的简单学习 建立Tcp通信 服务器端 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace TcpSocket { //服务器端 class Program { static void Main

Linux下TCP网络编程与基于Windows下C#socket编程间通信

一.linux下TCP网络编程基础,需要了解相关函数 Socket():用于套接字初始化. Bind():将 socket 与本机上的一个端口绑定,就可以在该端口监听服务请求. Listen():使socket处于被动的监听模式,并为该  socket  建立一个输入数据队列,将到达的服务器, 请求保存在此队列中,直到程序处理他们. Accept():让服务器接收客户的连接请求. Connect():客户端使用connect函数来配置 socket并与远端服务器建立一个 TCP 连接. Clos

Linux下TCP网络编程与基于Windows下C#socket编程之间通信

一.linux下TCP网络编程基础,需要了解相关函数 Socket():用于套接字初始化. Bind():将 socket 与本机上的一个端口绑定,就可以在该端口监听服务请求. Listen():使socket处于被动的监听模式,并为该  socket  建立一个输入 数据队列,将到达的服务器, 请求保存在此队列中,直到程序处理他们. Accept():让服务器接收客户的连接请求. Connect():客户端使用connect函数来配置 socket并与远端服务器建立一个 TCP 连接. Clo

linux 网络编程之最简单的tcp通信服务端

编写一个最为简单的tcp通信服务端.代码如下: #include <iostream> #include <cstring> using namespace std; #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <uni

linux 网络编程之最简单的tcp通信客户端

编写一个最为简单的tcp通信客户端.代码如下: #include <iostream> #include <cstring> using namespace std; #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> int main() { /*创

linux下java程序与C语言程序通过SOCKET通信的简单例子

linux下java程序与C语言程序通过SOCKET通信的简单例子 今天上午实验了java程序与c语言程序通过socket进行通信.由于没学过java,因此只是编写了C语言端的代码,java端的代码是从网上别的文章中找的,经过少量修改后与C语言端程序通信成功. 本例中C语言端作为服务器,java端作为客户端 代码如下: /****************** server program *****************/ #include <stdio.h> #include <sy