c# socket网络编程接收发送数据示例代码
程序员文章站
2024-02-22 20:31:29
代码分2块,server端:
复制代码 代码如下:class program { &nb...
代码分2块,server端:
复制代码 代码如下:
class program
{
static void main(string[] args)
{
tcplistener lsner = new tcplistener(9000);
lsner.start();
console.writeline("started in port: 9000");
while (true)
{
tcpclient client=lsner.accepttcpclient();
console.writeline("new client received. hashcode: {0}", client.gethashcode());
threadpool.queueuserworkitem(new waitcallback(processtcpclient), client);
}
console.readkey();
}
private static void processtcpclient(object state)
{
tcpclient client=state as tcpclient;
if(client==null)
console.writeline("client is null");
networkstream ns=client.getstream();
streamwriter sw = new streamwriter(ns);
sw.writeline("welcome.");
sw.flush();
sw.close();
client.close();
}
client端:
复制代码 代码如下:
class program
{
static void main(string[] args)
{
ipaddress address = ipaddress.parse("127.0.0.1");
ipendpoint ep=new ipendpoint(address, 9000);
tcpclient client = new tcpclient();
client.connect(ep);
networkstream ns=client.getstream();
streamreader sr = new streamreader(ns);
console.writeline(sr.readtoend());
sr.close();
sr.dispose();
ns.close();
ns.dispose();
client.close();
console.readkey();
}
}