代码分享:
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 Socket练习
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text ="127.0.0.1";
Control.CheckForIllegalCrossThreadCalls = false;
}
Socket st;
IPEndPoint ipi;
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text=="开始监听")
{
st = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse("127.0.0.1");
ipi = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));
st.Bind(ipi);
st.Listen(10);
textBox3.AppendText("监听成功\r\n");
button1.Text = "停止监听";
Thread td = new Thread(Accept);
td.IsBackground = true;
td.Start(st);
}
else
{
if (st != null)
{
ska.Close();
st.Close();
st = null;
}
button1.Text = "开始监听";
}
}
Socket ska;
void Accept(object st)
{
Socket sa = st as Socket;
while (true)
{
try
{
ska = sa.Accept();
textBox3.AppendText("客户端地址:" + ska.RemoteEndPoint.ToString() + "连接成功\r\n");
Thread tsend = new Thread(Receive);
tsend.IsBackground = true;
tsend.Start(ska);
}
catch
{
return;
}
}
}
void Receive(object s)
{
ska = s as Socket;
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 2];
int r = ska.Receive(buffer);
if (r == 0)
{
break;
}
string str = System.Text.Encoding.UTF8.GetString(buffer, 0, r);
textBox3.AppendText("客户端回应:" + ska.RemoteEndPoint.ToString() + ":" + str+"\r\n");
byte[] b= System.Text.Encoding.Default.GetBytes("服务器回应:"+(str.Contains("你好")?"你好":"服务器接收到了数据"+str+ "\r\n"));
ska.Send(b);
}
catch
{
return;
}
}
}
byte[] b1 = new byte[1024 * 1024 * 2];
private void button2_Click(object sender, EventArgs e)
{
try
{
Socket send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
send.Connect(ipi);
textBox4.AppendText("客户端:" + textBox5.Text + "\r\n");
Thread t = new Thread(recServer);
t.IsBackground = true;
t.Start(send);
Thread t1 = new Thread(sendServer);
t1.IsBackground = true;
t1.Start(send);
}catch(Exception ex)
{
textBox4.AppendText("客户端:" + ex + "\r\n");
}
}
void recServer(object s)
{
Socket send = s as Socket;
while (true)
{
int i;
string str="";
try
{
i = send.Receive(b1);
if (i == 0)
{
break;
}
str = System.Text.Encoding.Default.GetString(b1, 0, i);
textBox4.AppendText(str + "\r\n");
}
catch
{
textBox4.AppendText("客户端:" + str + "\r\n");
return;
}
}
}
void sendServer(object s)
{
Socket send1 = s as Socket;
int i = send1.Send(System.Text.Encoding.UTF8.GetBytes(textBox5.Text.Trim()));
send1.Shutdown(SocketShutdown.Send);
}
}
}