您的位置:首页 > 理论基础 > 计算机网络

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

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: