//socket基本编程
//服务端:
using system.net;
using system.net.sockets;
using system.text;
using system.threading;
thread mythread ;
socket socket;
// 清理所有正在使用的资源。
protected override void dispose( bool disposing )
{
try
{
socket.close();//释放资源
mythread.abort ( ) ;//中止线程
}
catch{ }
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
public static ipaddress getserverip()
{
iphostentry ieh=dns.gethostbyname(dns.gethostname());
return ieh.addresslist[0];
}
private void beginlisten()
{
ipaddress serverip=getserverip();
ipendpoint iep=new ipendpoint(serverip,8000);
socket=new socket(addressfamily.internetwork,sockettype.stream,protocoltype.tcp);
byte[] bytemessage=new byte[100];
this.label1.text=iep.tostring();
socket.bind(iep);
// do
while(true)
{
try
{
socket.listen(5);
socket newsocket=socket.accept();
newsocket.receive(bytemessage);
string stime = datetime.now.toshorttimestring ( ) ;
string msg=stime+":"+"message from:";
msg+=newsocket.remoteendpoint.tostring()+encoding.default.getstring(bytemessage);
this.listbox1.items.add(msg);
}
catch(socketexception ex)
{
this.label1.text+=ex.tostring();
}
}
// while(bytemessage!=null);
}
//开始监听
private void button1_click(object sender, system.eventargs e)
{
try
{
mythread = new thread(new threadstart(beginlisten));
mythread.start();
}
catch(system.exception er)
{
messagebox.show(er.message,"完成",messageboxbuttons.ok,messageboxicon.stop);
}
}
//客户端:
using system.net;
using system.net.sockets;
using system.text;
private void button1_click(object sender, system.eventargs e)
{
beginsend();
}
private void beginsend()
{
string ip=this.txtip.text;
string port=this.txtport.text;
ipaddress serverip=ipaddress.parse(ip);
int serverport=convert.toint32(port);
ipendpoint iep=new ipendpoint(serverip,serverport);
byte[] bytemessage;
// do
// {
socket socket=new socket(addressfamily.internetwork,sockettype.stream,protocoltype.tcp);
socket.connect(iep);
bytemessage=encoding.ascii.getbytes(textbox1.text);
socket.send(bytemessage);
socket.shutdown(socketshutdown.both);
socket.close();
// }
// while(bytemessage!=null);
}
基于tcp协议的发送和接收端
tcp协议的接收端
using system.net.sockets ; //使用到tcplisten类
using system.threading ; //使用到线程
using system.io ; //使用到streamreader类
int port = 8000; //定义侦听端口号
private thread ththreadread; //创建线程,用以侦听端口号,接收信息
private tcplistener tltcplisten; //侦听端口号
private bool blistener = true; //设定标示位,判断侦听状态
private networkstream nsstream; //创建接收的基本数据流
private streamreader srread;
private system.windows.forms.statusbar statusbar1;
private system.windows.forms.button button1;
private system.windows.forms.listbox listbox1; //从网络基础数据流中读取数据
private tcpclient tcclient ;
private void listen ( )
{
try
{
tltcplisten = new tcplistener ( port ) ; //以8000端口号来初始化tcplistener实例
tltcplisten.start ( ) ; //开始监听
statusbar1.text = "正在监听" ;
tcclient = tltcplisten.accepttcpclient ( ) ; //通过tcp连接请求
nsstream = tcclient.getstream ( ) ; //获取用以发送、接收数据的网络基础数据流
srread=new streamreader(nsstream);//以得到的网络基础数据流来初始化streamreader实例
statusbar1.text = "已经连接!";
while( blistener ) //循环侦听
{
string smessage = srread.readline();//从网络基础数据流中读取一行数据
if ( smessage == "stop" ) //判断是否为断开tcp连接控制码
{
tltcplisten.stop(); //关闭侦听
nsstream.close(); //释放资源
srread.close();
statusbar1.text = "连接已经关闭!" ;
ththreadread.abort(); //中止线程
return;
}
string stime = datetime.now.toshorttimestring ( ) ; //获取接收数据时的时间
listbox1.items.add ( stime + " " + smessage ) ;
}
}
catch ( system.security.securityexception )
{
messagebox.show ( "侦听失败!" , "错误" ) ;
}
}
//开始监听
private void button1_click(object sender, system.eventargs e)
{
ththreadread = new thread ( new threadstart ( listen ) );
ththreadread.start();//启动线程
button1.enabled=false;
}
// 清理所有正在使用的资源。
protected override void dispose( bool disposing )
{
try
{
tltcplisten.stop(); //关闭侦听
nsstream.close();
srread.close();//释放资源
ththreadread.abort();//中止线程
}
catch{}
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
tcp协议的发送端
using system.net.sockets; //使用到tcplisten类
using system.threading; //使用到线程
using system.io; //使用到streamwriter类
using system.net; //使用ipaddress类、iphostentry类等
private streamwriter swwriter; //用以向网络基础数据流传送数据
private networkstream nsstream; //创建发送数据的网络基础数据流
private tcpclient tcpclient;
private system.windows.forms.button button1;
private system.windows.forms.textbox textbox1;
private system.windows.forms.button button2;
private system.windows.forms.textbox textbox2;
private system.windows.forms.statusbar statusbar1;
private system.windows.forms.label label1;
private system.windows.forms.label label2; //通过它实现向远程主机提出tcp连接申请
private bool tcpconnect = false; //定义标识符,用以表示tcp连接是否建立
//连接
private void button1_click(object sender, system.eventargs e)
{
ipaddress ipremote ;
try
{
ipremote = ipaddress.parse ( textbox1.text ) ;
}
catch //判断给定的ip地址的合法性
{
messagebox.show ( "输入的ip地址不合法!" , "错误提示!" ) ;
return ;
}
iphostentry iphost ;
try
{
iphost = dns.resolve ( textbox1.text ) ;
}
catch //判断ip地址对应主机是否在线
{
messagebox.show ("远程主机不在线!" , "错误提示!" ) ;
return ;
}
string shostname = iphost.hostname ;
try
{
tcpclient tcpclient = new tcpclient(shostname,8000);//对远程主机的8000端口提出tcp连接申请
nsstream = tcpclient.getstream();//通过申请,并获取传送数据的网络基础数据流
swwriter = new streamwriter(nsstream);//使用获取的网络基础数据流来初始化streamwriter实例
button1.enabled = false ;
button2.enabled = true ;
tcpconnect = true ;
statusbar1.text = "已经连接!" ;
}
catch
{
messagebox.show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ;
return ;
}
}
//发送
private void button2_click(object sender, system.eventargs e)
{
if (textbox2.text !="")
{
swwriter.writeline(textbox2.text);//刷新当前数据流中的数据
swwriter.flush();
}
else
{
messagebox.show("发送信息不能为空!","错误提示!");
}
}
// 清理所有正在使用的资源。
protected override void dispose( bool disposing )
{
if ( tcpconnect )
{
swwriter.writeline ( "stop" ) ; //发送控制码
swwriter.flush (); //刷新当前数据流中的数据
nsstream.close (); //清除资源
swwriter.close ();
}
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
新闻热点
疑难解答