tcp助手类编程 暑期学习笔记(五)
2008-08-11 16:04
447 查看
tcp助手类是在socket层上建立的,可以直接通过client或server属性设置或获取。
#region usings 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.Threading; #endregion namespace Client { public partial class TalkClient : Form { #region Parameters TcpClient tcpc,tcpc2,tcpcb,tcpcr; TcpListener tcpl; NetworkStream ns; Thread threadR; Thread threadL; delegate void AppendItem(object o); AppendItem AddItem; void addItem(object o) { listBox.Items.Add(o); } #endregion #region Events public TalkClient() { InitializeComponent(); AddItem = new AppendItem(addItem); } private void btListen_Click(object sender, EventArgs e) { } private void TalkClient_Load(object sender, EventArgs e) { } private void btCnnect_Click(object sender, EventArgs e) { string target = txtTarget.Text.Trim(); IPAddress ipa = Dns.GetHostAddresses(target)[0]; IPEndPoint ipep = new IPEndPoint(ipa, 2008); tcpc = new TcpClient(); try { tcpc.Connect(ipep); listBox.Items.Add("connected!"); ns = tcpc.GetStream(); tcpcr = tcpc; threadR = new Thread(new ThreadStart(receiveData)); threadR.IsBackground = true; threadR.Start(); listBox.Items.Add("thread receive started!"); } catch (Exception exc) { MessageBox.Show(exc.Message); } tcpc2 = new TcpClient(); tcpc2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); try { tcpc2.Connect(ipep); listBox.Items.Add("Connection 2 connected!"); } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void btSend_Click(object sender, EventArgs e) { string data = txtMessage.Text.Trim(); try { byte[] buf = Encoding.Unicode.GetBytes(data); ns.Write(buf, 0, buf.Length); } catch (Exception exc) { listBox.Items.Add(exc.Message); throw; } } #endregion #region Methods void receiveData() { string data = string.Empty; byte[] buf = new byte[1024]; int len = 0; while (true) { len = tcpcr.Available; if ( len != 0) { ns.Read(buf, 0, len); data = Encoding.Unicode.GetString(buf, 0, len); listBox.Invoke(AddItem, data); } } } #endregion } }
相关文章推荐
- TCP/IP网络编程 学习笔记_1 --网络编程入门
- [学习笔记]Java网络编程之TCP通讯
- TCP-IP学习笔记六:Netty使用--简单通信编程2
- 19. JAVA 网络编程 Part 1 (IP与InetAddress类、URL与URLConnection类、URLEncoder与URLDecoder类、TCP&UDP)---- 学习笔记
- c#网络编程学习笔记02_Tcp编程(上)
- 关于Filezilla 以及TCP/IP网络串口助手的学习笔记
- java 网络编程 tcp黑马程序员学习笔记(4)
- Linux-网络编程学习笔记之tcp
- TCP/IP网络编程 学习笔记_8 --优雅地断开套接字连接
- Linux网络编程-学习笔记(基础TCP套接字函数)
- TCP/IP网络编程 学习笔记_8 --优雅地断开套接字连接
- TCP-IP学习笔记三:NIO的网络编程-单线程实例
- Unix网络编程学习笔记之第4章 基于TCP套接字编程
- 网络编程学习笔记二(实现一个基于简单TCP的用户注册程序)
- 网络编程学习笔记(tcp_connect函数)
- TCP-IP学习笔记二:NIO的网络编程Buffer简单使用
- TCP/IP网络编程 学习笔记_8 --优雅地断开套接字连接
- c#网络编程学习笔记02_Tcp编程(中)_简单的同步tcp聊天程序
- java网络编程 tcp 黑马程序员学习笔记(11)
- 黑马程序员_学习笔记:15) 网络编程:Socket(udp、tcp)