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();
}