C# socket 编程
C# socket 编程
view plaincopy to clipboardprint?
using system
using system.collections.generic
using system.linq
using system.text
using system.net.sockets
using system.net
using system.threading
namespace sockettest
{
class program
{
static void main(string[] args)
{
threadstart ts1 = socketsend
threadstart ts2 = socketreceive
thread t1 = new thread(ts1)
thread t2 = new thread(ts2)
t1.start()
t2.start()
console.readline()
}
private void writewebip()
{
var a = system.net.dns.gethostaddresses(" www.163.com" )
foreach (var temp in a)
{
var tmp = temp.getaddressbytes()
foreach (var tmp2 in tmp)
{
console.write(tmp2.tostring() + " ." )
}
console.writeline()
}
}
//通过socket发送
private static void socketsend()
{
//准备发送的数据
byte[] sendbyte={110 074 007 074}
try
{
//利用本机测试
var address = dns.gethostaddresses(" localhost" ).first()
ipendpoint ipendpoint = new ipendpoint(address 5714)
socket socket = new socket(addressfamily.internetwork sockettype.stream protocoltype.tcp)
socket.connect(ipendpoint)
if (socket.connected)
{
console.writeline(" socket开始发送数据" )
socket.send(sendbyte)
}
}
catch (exception 1)
{
console.writeline( 1.tostring())
}
}
//通过socket接收
private static void socketreceive()
{
byte[] receivebyte=new byte [4]
socket socket = new socket(addressfamily.internetwork sockettype.stream protocoltype.tcp)
socket.bind(new ipendpoint(ipaddress.any 5714))
socket.listen((int)socketoptionname.maxconnections)
var a = socket.accept()
if (a != null)
{
if (a.connected)
{
console.writeline(" socket开始接收数据" )
a.receive(receivebyte)
foreach (var temp in receivebyte)
{
console.write(temp.tostring ()+" " )
}
}
}
}
}
}