using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SocketService
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
//设置服务状态
public bool serviceState = true;
//侦听
TcpListener listener;
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 开始监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//ip
IPAddress ip = IPAddress.Parse("127.0.0.1");
//侦听
listener = new TcpListener(ip,8036);
listener.Start();//开始监听
//创建线程
Thread myThread = new Thread(listenerCLient);
myThread.Start();//开启线程
txtMessage.Text = "开始侦听
";
}
/// <summary>
/// 接收客户端消息
/// </summary>
public void listenerCLient()
{
while (serviceState)
{
try
{
//接收一个Client
TcpClient client = listener.AcceptTcpClient();
byte[] buffer = new byte[client.SendBufferSize];
//获取网络流
NetworkStream stream = client.GetStream();
//读取数据
stream.Read(buffer,0,buffer.Length);
//关闭流
stream.Close();
//关闭连接
client.Close();
//转换格式
txtMessage.Text += "来自客户端的消息:"+Encoding.Default.GetString(buffer).Trim(' ')+"
";
}
catch (Exception)
{
TcpClient client = null;
}
}
}
/// <summary>
/// 关闭
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
serviceState = false;
listener.Stop();//停止监听
txtMessage.Text += "停止监听
";
}
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//连接
TcpClient client = new TcpClient("127.0.0.1",8036);
//转换格式
byte[] buffer = Encoding.Default.GetBytes(txtMessage.Text);
//获取流
NetworkStream stream = client.GetStream();
//写入
stream.Write(buffer, 0, buffer.Length);
//刷新
stream.Flush();
//关闭
stream.Close();
client.Close();
}