发现一个好帖子
你得学会并且学得会的Socket编程基础知识 - 陈希章 - 博客园
客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Net;
namespace SockForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSend_Click(object sender, EventArgs e)
{
string ip = this.txtIP.Text.Trim();
string port = this.txtPort.Text.Trim();
string message = this.txtMessage.Text.Trim();
if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(port) || string.IsNullOrEmpty(message))
{
MessageBox.Show("不能为空!");
return;
}
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress iPAddress = IPAddress.Parse(ip);
socket.Connect(new IPEndPoint(iPAddress, int.Parse(port)));
string sendMessage = this.txtMessage.Text.Trim();
socket.Send(Encoding.ASCII.GetBytes(sendMessage));
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
socket.Close();
}
}
}
}
客户端窗体
服务器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace ListenerForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(MyListen));
thread.Start();
}
//委托
protected delegate void ShowContentDelegate(string content);
private void MyListen()
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),19522));
while(true)
{
serverSocket.Listen(0);
Socket socket = serverSocket.Accept();
byte[] data = new byte[1024];
int bytes = socket.Receive(data,data.Length,0);
ShowContentDelegate myContent = new ShowContentDelegate(ShowContent); //绑定委托与方法
Invoke(myContent,new object[] {Encoding.ASCII.GetString(data,0,bytes)});
}
}
public void ShowContent(string content)
{
this.txtReceive.Text += content + "\r\n";
}
}
}
服务器窗体