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 socketWF
{
public partial class FormS : Form
{
IPAddress ip;
IPEndPoint point;
public FormS()
{
InitializeComponent();
ServerListen();
}
private void ServerListen()
{
//ip地址
ip = IPAddress.Parse(txtIP.Text);
// IPAddress ip = IPAddress.Any;
//端口号
point = new IPEndPoint(ip, int.Parse(txtPort.Text));
//创建监听用的Socket
/*
AddressFamily.InterNetWork:使用 IP4地址。
SocketType.Stream:支持可靠、双向、基于连接的字节流,而不重复数据。此类型的 Socket 与单个对方主机进行通信,
并且在通信开始之前需要远程主机连接。Stream 使用传输控制协议 (Tcp) ProtocolType 和 InterNetworkAddressFamily。
ProtocolType.Tcp:使用传输控制协议。
*/
//使用IPv4地址,流式socket方式,tcp协议传递数据
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建好socket后,必须告诉socket绑定的IP地址和端口号。
//让socket监听point
try
{
//socket监听哪个端口
socket.Bind(point);
//同一个时间点过来60个客户端,排队
socket.Listen(60);
ShowMsg("服务器开始监听");
Thread thread = new Thread(AcceptInfo);
thread.IsBackground = true;
thread.Start(socket);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
//记录通信用的Socket
Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
// private Socket client;
void AcceptInfo(object o)
{
Socket socket = o as Socket;
while (true)
{
//通信用socket
try
{
//创建通信用的Socket
Socket tSocket = socket.Accept();
string point = tSocket.RemoteEndPoint.ToString();
//IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint;
//string me = Dns.GetHostName();//得到本机名称
//MessageBox.Show(me);
ShowMsg(point + "连接成功!");
ComboBoxAddItems(point);
dic.Add(point, tSocket);
//接收消息
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(tSocket);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
break;
}
}
}
//接收消息
void ReceiveMsg(object o)
{
Socket client = o as Socket;
while (true)
{
//接收客户端发送过来的数据
try
{
//定义byte数组存放从客户端接收过来的数据
byte[] buffer = new byte[1024 * 1024];
//将接收过来的数据放到buffer中,并返回实际接受数据的长度
int n = client.Receive(buffer);
//将字节转换成字符串
string words = Encoding.UTF8.GetString(buffer, 0, n);
ShowMsg(client.RemoteEndPoint.ToString() + ":" + words);
}
catch (Exception ex)
{
if (!client.Connected) ComboBoxRoMoveItems(client.RemoteEndPoint.ToString());
ShowMsg(ex.Message);
break;
}
}
}
delegate void SetTextCallback(string msg);
public void ShowMsg(string msg)
{
if (this.txtLog.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(ShowMsg);
this.Invoke(d, new object[] { msg });
}
else
{
this.txtLog.AppendText(msg + "\r\n");
}
}
delegate void SetComboBox(String msg);
public void ComboBoxAddItems(string msg)
{
if (this.cboIpPort.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(ComboBoxAddItems);
this.Invoke(d, new object[] { msg });
}
else
{
this.cboIpPort.Items.Add(msg);
}
}
public void ComboBoxRoMoveItems(string msg)
{
if (this.cboIpPort.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(ComboBoxRoMoveItems);
this.Invoke(d, new object[] { msg });
}
else
{
this.cboIpPort.Items.Remove(msg);
cboIpPort.SelectedIndex = -1;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void Clearbtn_Click(object sender, EventArgs e)
{
this.txtLog.Text = "";
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
string ip = cboIpPort.Text;
if (cboIpPort.Text.Length > 5)
{
byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
dic[ip].Send(buffer);
ShowMsg(point.ToString() + ":" + txtMsg.Text);
}
else
{
}
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
}
}
//客户端===================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace socketCWF
{
public partial class FormC : Form
{ //客户端参数
Socket client;
IPAddress ip;
IPEndPoint point;
bool isExits = false;
public FormC()
{
InitializeComponent();
}
//定意通讯协议创建socket服务实例
private void FormC_Load(object sender, EventArgs e)
{
ip = IPAddress.Parse(txtIP.Text);
point = new IPEndPoint(ip, int.Parse(txtPort.Text));
Thread serverConnetThread = new Thread(ServerConnetThread);
serverConnetThread.IsBackground = true;
serverConnetThread.Start();
}
//客户端发起连接请求函数
private void ServerConnet()
{
try
{
//连接到服务器
if (client != null) client.Close();
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(point);
ShowMsg("连接成功");
ShowMsg("服务器:" + client.RemoteEndPoint.ToString());
ShowMsg("客户端:" + client.LocalEndPoint.ToString());
//连接成功后,就可以接收服务器发送的信息了
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start();
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
private void ServerConnetThread()
{
while (!isExits)
{
if (client == null || !client.Connected)
{
ServerConnet();
}
Thread.Sleep(5000);
}
}
//接收服务器的消息
void ReceiveMsg()
{
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024];
int n = client.Receive(buffer);
string s = Encoding.UTF8.GetString(buffer, 0, n);
ShowMsg(point.ToString() + ":" + s);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
break;
}
}
}
delegate void SetTextCallback(string msg);
//文本框接收服务器信息
public void ShowMsg(string msg)
{
if (this.txtInfo.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(ShowMsg);
this.Invoke(d, new object[] { msg });
}
else
{
this.txtInfo.AppendText(msg + "\r\n");
}
}
private void btnSend_Click(object sender, EventArgs e)
{
//客户端给服务器发消息
if (client != null)
{
try
{
ShowMsg(client.RemoteEndPoint + ":" + txtInfo.Text);
byte[] buffer = Encoding.UTF8.GetBytes(txtInfo.Text);
client.Send(buffer);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
}
//清除信息
private void Clearbtn_Click(object sender, EventArgs e)
{
this.txtInfo.Text = "";
}
}
}
标签:socket,void,练习,System,client,new,using,本机,ShowMsg From: https://www.cnblogs.com/zhangfengggg/p/17222112.html