using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Net;us ...
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 = "開始偵聽\r\n";
}
/// <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('\0')+"\r\n";
}
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 += "停止監聽\r\n";
}
}
}
/// <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();
}