服务端代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace SocketServer
{
class Server
{
//创建监听对象
private static TcpListener tcpServer = null;
public Server()
{
//获取本机ip地址
IPAddress iPAddress = IPAddress.Any;
//指定在哪个端口上监听
tcpServer = new TcpListener(iPAddress, 999);
//999是端口号,可以随便改 0-1024,主要不要和什么80,8080之类的常用端口号相冲突哦。
//开始监听
tcpServer.Start();
Console.WriteLine("监听已启动......");
//把收发放到后台线程运行
Thread t1 = new Thread(ExceMethod);
t1.IsBackground = true;
t1.Start();
}
private static void ExceMethod()
{
byte[] msg = Encoding.UTF8.GetBytes("服务端发出的数据");
while (true)
{
//接收数据的缓存
byte[] bytes = new byte[256];
//接收监听到的客户端
TcpClient client = tcpServer.AcceptTcpClient();
while (true)
{
try
{
//把客户端的发送的数据存到缓冲区
int i = client.Client.Receive(bytes);
Console.WriteLine(DateTime.Now.ToString("G") + "接受:" + Encoding.UTF8.GetString(bytes));
Console.WriteLine("\n");
//发送数据给客户端
client.Client.Send(msg);
}
catch
{
break;
}
}
client.Close();
Thread.Sleep(1000);//10000单位是毫秒,系统在运行过程中,稍微有点停顿,个人感觉会更好一点。
}
}
}
}
客户端代码:
using System;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace SocketClient
{
class Client
{
//创建客户端
private static TcpClient client = new TcpClient();
public Client()
{
//和服务器连接
client.Connect("127.0.0.1", 999);
Console.WriteLine("连接成功......");
//在线程收发数据
Thread t1 = new Thread(ExceMethod);
t1.IsBackground = true;
t1.Start();
}
private static void ExceMethod()
{
while (true)
{
byte[] data = Encoding.UTF8.GetBytes("客户端发出的数据");
//接收连接服务器的socket对象
Socket socket = client.Client;
//给服务器发送数据
socket.Send(data, data.Length, SocketFlags.None);
Console.WriteLine("发送成功:" + Encoding.UTF8.GetString(data));
//接收服务器发送的数据
socket.Receive(data, SocketFlags.None);
Console.WriteLine("接受数据:" + Encoding.UTF8.GetString(data));
Thread.Sleep(1000);
}
}
}
}