view plainprint?
//Socket基本编程
//服务端
using SystemNet
using SystemNetSockets
using SystemText
using SystemThreading
Thread mythread
Socket socket
// 清理所有正在使用的资源
protected override void Dispose( bool disposing )
{
try
{
socketClose()//释放资源
mythreadAbort ( ) //中止线程
}
catch{ }
if( disposing )
{
if (components != null)
{
componentsDispose()
}
}
baseDispose( disposing )
}
public static IPAddress GetServerIP()
{
IPHostEntry ieh=DnsGetHostByName(DnsGetHostName())
return iehAddressList[]
}
private void BeginListen()
{
IPAddress ServerIp=GetServerIP()
IPEndPoint iep=new IPEndPoint(ServerIp)
socket=new Socket(AddressFamilyInterNetworkSocketTypeStreamProtocolTypeTcp)
byte[] byteMessage=new byte[]
thislabelText=iepToString()
socketBind(iep)
// do
while(true)
{
try
{
socketListen()
Socket newSocket=socketAccept()
newSocketReceive(byteMessage)
string sTime = DateTimeNowToShortTimeString ( )
string msg=sTime++Message from
msg+=newSocketRemoteEndPointToString()+EncodingDefaultGetString(byteMessage)
thislistBoxItemsAdd(msg)
}
catch(SocketException ex)
{
thislabelText+=exToString()
}
}
// while(byteMessage!=null)
}
//开始监听
private void button_Click(object sender SystemEventArgs e)
{
try
{
mythread = new Thread(new ThreadStart(BeginListen))
mythreadStart()
}
catch(SystemException er)
{
MessageBoxShow(erMessage完成MessageBoxButtonsOKMessageBoxIconStop)
}
}
//客户端
using SystemNet
using SystemNetSockets
using SystemText
private void button_Click(object sender SystemEventArgs e)
{
BeginSend()
}
private void BeginSend()
{
string ip=thistxtipText
string port=thistxtportText
IPAddress serverIp=IPAddressParse(ip)
int serverPort=ConvertToInt(port)
IPEndPoint iep=new IPEndPoint(serverIpserverPort)
byte[] byteMessage
// do
// {
Socket socket=new Socket(AddressFamilyInterNetworkSocketTypeStreamProtocolTypeTcp)
socketConnect(iep)
byteMessage=EncodingASCIIGetBytes(textBoxText)
socketSend(byteMessage)
socketShutdown(SocketShutdownBoth)
socketClose()
// }
// while(byteMessage!=null)
}
基于TCP协议的发送和接收端
TCP协议的接收端
using SystemNetSockets //使用到TcpListen类
using SystemThreading //使用到线程
using SystemIO //使用到StreamReader类
int port = //定义侦听端口号
private Thread thThreadRead //创建线程用以侦听端口号接收信息
private TcpListener tlTcpListen //侦听端口号
private bool blistener = true //设定标示位判断侦听状态
private NetworkStream nsStream //创建接收的基本数据流
private StreamReader srRead
private SystemWindowsFormsStatusBar statusBar
private SystemWindowsFormsButton button
private SystemWindowsFormsListBox listBox //从网络基础数据流中读取数据
private TcpClient tcClient
private void Listen ( )
{
try
{
tlTcpListen = new TcpListener ( port ) //以端口号来初始化TcpListener实例
tlTcpListenStart ( ) //开始监听
statusBarText = 正在监听
tcClient = tlTcpListenAcceptTcpClient ( ) //通过TCP连接请求
nsStream = tcClientGetStream ( ) //获取用以发送接收数据的网络基础数据流
srRead=new StreamReader(nsStream)//以得到的网络基础数据流来初始化StreamReader实例
statusBarText = 已经连接!
while( blistener ) //循环侦听
{
string sMessage = srReadReadLine()//从网络基础数据流中读取一行数据
if ( sMessage == STOP ) //判断是否为断开TCP连接控制码
{
tlTcpListenStop() //关闭侦听
nsStreamClose() //释放资源
srReadClose()
statusBarText = 连接已经关闭!
thThreadReadAbort() //中止线程
return
}
string sTime = DateTimeNowToShortTimeString ( ) //获取接收数据时的时间
listBoxItemsAdd ( sTime + + sMessage )
}
}
catch ( SystemSecuritySecurityException )
{
MessageBoxShow ( 侦听失败! 错误 )
}
}
//开始监听
private void button_Click(object sender SystemEventArgs e)
{
thThreadRead = new Thread ( new ThreadStart ( Listen ) )
thThreadReadStart()//启动线程
buttonEnabled=false
}
// 清理所有正在使用的资源
protected override void Dispose( bool disposing )
{
try
{
tlTcpListenStop() //关闭侦听
nsStreamClose()
srReadClose()//释放资源
thThreadReadAbort()//中止线程
}
catch{}
if( disposing )
{
if (components != null)
{
componentsDispose()
}
}
baseDispose( disposing )
}
TCP协议的发送端
using SystemNetSockets //使用到TcpListen类
using SystemThreading //使用到线程
using SystemIO //使用到StreamWriter类
using SystemNet //使用IPAddress类IPHostEntry类等
private StreamWriter swWriter //用以向网络基础数据流传送数据
private NetworkStream nsStream //创建发送数据的网络基础数据流
private TcpClient tcpClient
private SystemWindowsFormsButton button
private SystemWindowsFormsTextBox textBox
private SystemWindowsFormsButton button
private SystemWindowsFormsTextBox textBox
private SystemWindowsFormsStatusBar statusBar
private SystemWindowsFormsLabel label
private SystemWindowsFormsLabel label //通过它实现向远程主机提出TCP连接申请
private bool tcpConnect = false //定义标识符用以表示TCP连接是否建立
//连接
private void button_Click(object sender SystemEventArgs e)
{
IPAddress ipRemote
try
{
ipRemote = IPAddressParse ( textBoxText )
}
catch //判断给定的IP地址的合法性
{
MessageBoxShow ( 输入的IP地址不合法! 错误提示! )
return
}
IPHostEntry ipHost
try
{
ipHost = DnsResolve ( textBoxText )
}
catch //判断IP地址对应主机是否在线
{
MessageBoxShow (远程主机不在线! 错误提示! )
return
}
string sHostName = ipHostHostName
try
{
TcpClient tcpClient = new TcpClient(sHostName)//对远程主机的端口提出TCP连接申请
nsStream = tcpClientGetStream()//通过申请并获取传送数据的网络基础数据流
swWriter = new StreamWriter(nsStream)//使用获取的网络基础数据流来初始化StreamWriter实例
buttonEnabled = false
buttonEnabled = true
tcpConnect = true
statusBarText = 已经连接!
}
catch
{
MessageBoxShow ( 无法和远程主机端口建立连接! 错误提示! )
return
}
}
//发送
private void button_Click(object sender SystemEventArgs e)
{
if (textBoxText !=)
{
swWriterWriteLine(textBoxText)//刷新当前数据流中的数据
swWriterFlush()
}
else
{
MessageBoxShow(发送信息不能为空!错误提示!)
}
}
// 清理所有正在使用的资源
protected override void Dispose( bool disposing )
{
if ( tcpConnect )
{
swWriterWriteLine ( STOP ) //发送控制码
swWriterFlush () //刷新当前数据流中的数据
nsStreamClose () //清除资源
swWriterClose ()
}
if( disposing )
{
if (components != null)
{
componentsDispose()
}
}
baseDispose( disposing )
}
资料引用