服务器端代码:
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TcpReceive
{
/// <summary>
/// 服务器端
/// </summary>
public partial class FrmReceive : Form
{
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 2222)); //2222端口
public FrmReceive()
{
InitializeComponent();
listener.Start(); //开始侦听端口
Thread acceptThread = new Thread(new ThreadStart(AcceptWorkThread));
acceptThread.Start(); //接受客户端请求
}
/// <summary>
/// 接收、解码
/// </summary>
private void AcceptWorkThread()
{
Socket socket = listener.AcceptSocket();
byte[] buffer = new byte[1024];
while (true)
{
int receiveCount = socket.Receive(buffer);
if (receiveCount > 0)
{
string recString = Encoding.UTF8.GetString(buffer, 0, receiveCount); //解码
ShowMsg(recString);
}
else
{
socket.Close();
break;
}
}
}
/// <summary>
/// 显示接收到的消息内容
/// </summary>
/// <param name="text"></param>
public void ShowMsg(string text)
{
rBoxRecevie.Text = text;
}
}
}
-----------------------------------------------------------------------
客户端代码:
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace TcpSend
{
/// <summary>
/// 客户端
/// </summary>
public partial class FrmSend : Form
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public FrmSend()
{
InitializeComponent();
}
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnConn_Click(object sender, EventArgs e)
{
IPAddress serverIp = IPAddress.Parse("192.168.1.102");
IPEndPoint iep = new IPEndPoint(serverIp, 2222);
socket.Connect(iep); //连接服务器
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
if (socket.Connected)
BeginSend();
else
MessageBox.Show("请先连接服务器!", "提示");
}
private void BeginSend()
{
byte[] byteMessage;
byteMessage = Encoding.UTF8.GetBytes(rBoxContent.Text);
socket.Send(byteMessage);
}
/// <summary>
/// 窗口关闭时释放socket
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmSend_FormClosing(object sender, FormClosingEventArgs e)
{
if (socket.Connected)
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
}