服务端
Socket socketWatch = null;
public string StrlocalAddr = "127.0.0.1";
public string Strport = "5555";
private void timer1_Tick(object sender, EventArgs e)
{
if (socketWatch == null)
{
timer1.Enabled = false;
// 创建负责监听的套接字,注意其中的参数;
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 获得文本框中的IP对象;
IPAddress address = IPAddress.Parse(StrlocalAddr);
// 创建包含ip和端口号的网络节点对象;
IPEndPoint endPoint = new IPEndPoint(address, int.Parse(Strport));
try
{
// 将负责监听的套接字绑定到唯一的ip和端口上;
socketWatch.Bind(endPoint);
}
catch (SocketException se)
{
MessageBox.Show("异常:" + se.Message);
return;
}
// 设置监听队列的长度;
socketWatch.Listen(10);
// 创建负责监听的线程;
Task a = Task.Factory.StartNew(() =>
{
while (true)
{
Socket sokConnection = socketWatch.Accept();
Task.Factory.StartNew(() =>
{
GetTcpListenString(sokConnection);
});
}
});
cf.f_writeLog(string.Format("服务器启动监听成功!({0}:{1})", StrlocalAddr, Strport), "系统消息:");
}
else
{
timer1.Enabled = true;
}
}
public void GetTcpListenString(Socket c)
{
try
{
Byte[] bytes = new Byte[524288];
String data = null;
AllSource = string.Empty;
while (true)
{
if (c.Poll(-1, SelectMode.SelectRead))
{
try
{
int i = c.Receive(bytes, bytes.Length, 0);
if(i == 0)
{
cf.f_writeLog("客户端连接正常断开", "通讯提示");
break;
}
//接收到的数据
data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
}
catch
{
cf.f_writeLog("客户端连接异常断开", "通讯提示");
break;
}
}
}
#endregion
}
catch (SocketException e)
{
MessageBox.Show("通讯关闭,请确定仪器开启!", "福建弘扬软件提醒您:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}
}
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace socket_client
{
class Program
{
static Socket clientSocket;
static void Main(string[] args)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接
Connect();
}
//连接客户端,连接后开始监听发送过来的消息并且把输入的信息发给服务端
static void Connect()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
//连接
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555));
//独立线程来接受来自服务端的数据
Thread receive = new Thread(Receive);
receive.Start(clientSocket);
//独立线程来发送数据给服务端
Thread send = new Thread(Send);
send.Start(clientSocket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Receive(object so)
{
Socket clientSocket = so as Socket;
while (true)
{
Console.ForegroundColor = ConsoleColor.Green; // 修改文字颜色为绿色
try
{
byte[] buffer = new byte[1024];
int len = clientSocket.Receive(buffer);
if (len > 0)
{
string msg = Encoding.UTF8.GetString(buffer);
Console.WriteLine("服务端说:"+ msg);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
break;
}
}
clientSocket.Close();
}
static void Send(object so)
{
Socket clientSocket = so as Socket;
string sendMsg = "123";
//编码
byte[] buffer = Encoding.UTF8.GetBytes(sendMsg);
//发送
clientSocket.Send(buffer);
}
}
}