socket编程简单服务器端和简单客户端

1.简单服务器端
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
private static int port = %%2;
private static Thread thThreadRead;
private static TcpListener TcpListen;
private static bool bListener = true;
private static Socket stRead;
*/
private static void Listen()
{
	try
	{
		TcpListen = new TcpListener(port);
		TcpListen.Start();
		stRead = TcpListen.AcceptSocket();
		EndPoint tempRemoteEP = stRead.RemoteEndPoint;
		IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
		IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address);
		string sHostName = host.HostName;
		while (bListener)
		{
			stRead.Send(Encoding.ASCII.GetBytes(%%1));
			string sTime = DateTime.Now.ToShortTimeString();
			Byte[] byRead = new Byte[1024];
			int iRead = stRead.ReceiveFrom(byRead, ref tempRemoteEP);
			Byte[] byText = new Byte[iRead];
			Array.Copy(byRead, 0, byText, 0, iRead);
			string line = System.Text.Encoding.Default.GetString(byRead);
		}
	}
	catch (System.Security.SecurityException)
	{
		//监听失败
	}
}
thThreadRead = new Thread(new ThreadStart(Listen));
thThreadRead.Start();

2.简单客户端
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
private static IPEndPoint dateTimeHost;
*/
string hostIPString=%%1;
string hostPortString=%%2;
IPAddress hostIP=IPAddress.Parse(hostIPString);
dateTimeHost=new IPEndPoint(hostIP,Int32.Parse(hostPortString));
Socket conn=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
conn.Connect(dateTimeHost);
int bytes=0;
Byte[] RecvBytes=new Byte[256];
bytes=conn.Receive(RecvBytes,RecvBytes.Length,0);
string RecvString=Encoding.ASCII.GetString(RecvBytes,0,bytes);
Console.WriteLine(RecvString);
conn.Shutdown(SocketShutdown.Both);
conn.Close();

3.获得本机IP
//using System.Net;
IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string %%1=null;
for (int i = 0; i < addressList.Length; i++)
{
	%%1 += addressList[i].ToString();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值