服务端代码
//这是服务端
Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skt.Bind(new IPEndPoint(IPAddress.Parse("10.0.0.193"), 2333));//前面的局域网内ip,后面是端口号,随便起,在本机 不被占用就行
skt.Listen(100);
while (true)//不断轮询,接收客户端发送的信息
{
Socket acceptskt = skt.Accept();//接收客户端信息
acceptskt.ReceiveTimeout = 3000;//
List<byte> data = new List<byte>();
byte[] buffer = new byte[1024];
int length = 0;
try
{
while ((length = acceptskt.Receive(buffer)) > 0)
{
for (int i = 0; i < length; i++)
{
data.Add(buffer[i]);
}
if (length < buffer.Length)
{
break;
}
}
}
catch { }
if (data.Count > 0)
{
Console.WriteLine(Encoding.Default.GetString(data.ToArray(), 0, data.Count));
}
acceptskt.Send(Encoding.Default.GetBytes("我收到你的信了"));
if (acceptskt.Connected)
{
acceptskt.Shutdown(SocketShutdown.Both);
}
acceptskt.Close();
}
客户端
string result = string.Empty;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect("10.0.0.193", 2333);
string senddata = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + new Random((int)DateTime.Now.Ticks).Next().ToString();
clientSocket.Send(Encoding.Default.GetBytes(senddata));
Console.WriteLine("我告诉服务器:"+ senddata);
clientSocket.ReceiveTimeout = 3000;
List<byte> data = new List<byte>();
byte[] buffer = new byte[1024];
int length = 0;
try
{
while ((length = clientSocket.Receive(buffer)) > 0)
{
for (int j = 0; j < length; j++)
{
data.Add(buffer[j]);
}
if (length < buffer.Length)
{
break;
}
}
}
catch { }
if (data.Count > 0)
{
result = encode.GetString(data.ToArray(), 0, data.Count);
}
Console.WriteLine("服务器对我说:" + result);