基于TCP的Socket基础例子
服务端的代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket clientSocket = null;
int tiaoshu = ; private void Form1_Load(object sender, EventArgs e)
{
try
{
this.txtPort.Text = "";
this.txtSend.Text = "服务端发送"; }
catch { }
} //创建并监听
private void listen()
{
try
{
//获取服务器IP
// clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //因为用的一台机器测试所以服务器的IP设置成了127.0.0.1,这里填写的是服务端的IP地址如:192.168.1.110
IPAddress HostIp = IPAddress.Parse("127.0.0.1"); //创建一个网络端点
IPEndPoint iep = new IPEndPoint(HostIp, Int32.Parse(this.txtPort.Text.Trim())); //创建服务端服务端套接字
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //将套接字与网络端点绑定
serverSocket.Bind(iep); serverSocket.Listen(); clientSocket = serverSocket.Accept(); if(!clientSocket.Connected)
{
clientSocket=null;
}
if(clientSocket!=null)
{
tiaoshu = ;
} }
catch { } }
Thread threadList;
// Socket clientSocket=null;
private void btnStart_Click(object sender, EventArgs e)
{
try
{
if (this.btnStart.Text == "启动服务")
{ this.btnStart.Text = "停止服务"; threadList = new Thread(new ThreadStart(listen)); threadList.Start(); timer1.Enabled = true; //this.lblState.Text = "连接成功!";
}
else {
this.btnStart.Text = "启动服务"; timer1.Enabled = false; threadList.Abort();
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close(); //this.lblState.Text = "连接失败!"; }
}
catch { }
} private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (clientSocket != null)
{
if (clientSocket.Connected)
{
this.lblState.Text = "连接成功!"; byte[] receiveBytes = new byte[]; if (clientSocket.Poll(, SelectMode.SelectRead))
{
int successReceiveBytes = clientSocket.Receive(receiveBytes);
this.txtReceive.Text = "客户端" + clientSocket.RemoteEndPoint.ToString()
+ "\r\n" + "接收" + System.Text.Encoding.UTF8.GetString(receiveBytes, , successReceiveBytes);
this.txtReceive.SelectionLength = txtReceive.Text.Length;
this.txtReceive.ScrollToCaret();
} }
else
{
this.lblState.Text = "连接失败!";
}
} }
catch { }
} private void btnSend_Click(object sender, EventArgs e)
{
try
{
if(clientSocket==null)
{
this.lblState.Text = "连接失败";
}else
{
string sendMessage = this.txtSend.Text.Trim();
byte[] message = System.Text.Encoding.UTF8.GetBytes(sendMessage);
int successSendMessage = clientSocket.Send(message,message.Length,SocketFlags.None); } }
catch { }
}
}
客户端的代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
this.txtIP.Text = "127.0.0.1";//服务端的IP地址,这里因为是服务端是本机写127.0.0.1,如服务端是192.168.1.110,这里应该写192.168.1.110
this.txtPort.Text = "";//服务端发布的端口号
this.txtSend.Text = "客户端发送";
} Socket clientSocket; private void btnStart_Click(object sender, EventArgs e)
{
try
{
IPAddress ip = IPAddress.Parse(this.txtIP.Text.Trim()); IPEndPoint iep = new IPEndPoint(ip,int.Parse(this.txtPort.Text.Trim())); clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); clientSocket.Connect(iep); clientSocket.ReceiveTimeout = ; clientSocket.SendTimeout = ; this.lblState.Text = "连接成功"; timer1.Enabled = true; }
catch {
}
} private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (clientSocket != null)
{
if (clientSocket.Connected)
{
byte[] receiveSocket=new byte[];
if(clientSocket.Poll(,SelectMode.SelectRead))
{
int successSocket = clientSocket.Receive(receiveSocket);
if(successSocket!=)
{
this.txtReceive.Text = "服务端" + System.Text.Encoding.UTF8.GetString(receiveSocket,,successSocket);
this.txtReceive.SelectionStart = this.txtReceive.Text.Length;
this.txtReceive.ScrollToCaret();
}
}
}
}
else {
this.lblState.Text = "连接失败!";
} }
catch { }
} private void btnSend_Click(object sender, EventArgs e)
{
try
{
if(clientSocket!=null)
{
if(clientSocket.Connected)
{
string sendMessage = this.txtSend.Text.Trim();
byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
int successSendBytes = clientSocket.Send(sendBytes,sendBytes.Length,SocketFlags.None); } }else{
this.lblState.Text="连接失败!";
} }
catch { }
}
}
展示效果如下