之前写的一个基于.NET Framework的局域网通信的软件,有些bug,不过只是为了探究一下socket通信,后续技术熟练以后会对它进行二次迭代,最开始做了一个基于控制台的,后面想了一下,还是需要用可视化界面,所以选择了.NET Framework框架又实现了一遍,也遇到了一些新的问题,最终实现了基本的聊天的发送和接收功能,通信类如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace Communication_software_windows
{
class Sockt_communication
{
public string user_name = "default";
public string _ip = string.Empty;
private string _ip1 = string.Empty;
private int _port = 0;
private int port1 = 0;
public Socket _socket = null;
public Socket _socket1 = null;
private byte[] buffer = new byte[1024 * 1024 * 2];
private byte[] buffer1 = new byte[1024 * 1024 * 2];
private IPAddress address;
private IPEndPoint endPoint;
public TextBox receive_box;
public TextBox sendmessage_box;
delegate void UpdateUIDelegate(string text);
void UpdateUI(string text)
{
receive_box.Text += text;
}
//无参构造函数
public Sockt_communication()
{
}
public Sockt_communication(string ip, string ip1, int port, int port1, string user_name)
{
this._ip = ip;
this._ip1 = ip1;
this._port = port;
this.port1 = port1;
this.user_name = user_name;
}
public Sockt_communication(int port, int port1, string user_name)
{
this._ip = "127.0.0.1";
this._port = port;
this.port1 = port1;
this.user_name = user_name;
}
public bool Init_prepare_link(string self_ip, string target_ip, int self_port, int target_port, string user_name, Label tishi)
{
try
{
this._ip = self_ip;
this._ip1 = target_ip;
this._port = Convert.ToInt32(self_port);
this.port1 = Convert.ToInt32(target_port);
//实例化套接字(IP4寻找协议,流式协议,TCP协议)
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建IP对象
this.address = IPAddress.Parse(IPAddress.Any.ToString());
//创建网络端口,包括ip和端口
this.endPoint = new IPEndPoint(this.address, _port);
//设置用户昵称
this.user_name = user_name;
//绑定套接字
_socket.Bind(endPoint);
tishi.Text = "正在设置";
//设置最大连接数
_socket.Listen(int.MaxValue);
tishi.Text = "本机登录成功,开始监听";
Form2 form = new Form2();
form.ShowDialog();
ListenClientConnect();
}
catch
{
tishi.Text = "本机登录失败,请输入正确的局域网主机地址";
}
return true;
}
public void ListenClientConnect()
{
try
{
//Socket创建的新连接
Thread thread = new Thread(ReceiveMessage);
thread.Start();
}
catch (Exception)
{
receive_box.Text += "接收功能尝试连接....\r\n";
}
}
/// <summary>
/// 接收客户端消息
/// </summary>
/// <param name="socket">来自客户端的socket</param>
private void ReceiveMessage()
{
Socket clientSocket = null;
try
{
clientSocket = _socket.Accept();
clientSocket.Send(Encoding.UTF8.GetBytes("接收消息功能连接成功...\r\n"));
}
catch (SocketException ex)
{
receive_box.BeginInvoke(new Action(() => {
receive_box.Text += "接收消息功能连接失败,请重试...\r\n";
}));
Console.WriteLine("Socket异常: " + ex.Message);
if (clientSocket != null)
{
clientSocket.Close();
}
}
catch (Exception ex)
{
receive_box.BeginInvoke(new Action(() => {
receive_box.Text += "接收消息功能连接失败,请重试...\r\n";
}));
Console.WriteLine("发生异常: " + ex.Message);
if (clientSocket != null)
{
clientSocket.Close();
}
return;
}
while (true)
{
try
{
//获取从客户端发来的数据
int length = clientSocket.Receive(buffer);
Console.WriteLine("正在接收数据!...");
string str = "接收到对方"+ clientSocket.RemoteEndPoint.ToString()+ "消息内容:\r\n------------------------\r\n"+Encoding.UTF8.GetString(buffer, 0, length)+ "\r\n------------------------\r\n";
//UpdateUIDelegate degit = UpdateUI;
//degit(str);
receive_box.BeginInvoke(new Action(() => {
receive_box.Text += str;
}));
Console.WriteLine(str);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
receive_box.BeginInvoke(new Action(() => {
receive_box.Text += "尝试连接...\r\n";
}));
break;
}
}
}
public void StartClient()
{
if (_socket1 == null)
{
//实例化套接字(IP4寻址地址,流式传输,TCP协议)
_socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建IP对象
IPAddress address = IPAddress.Parse(_ip1);
//创建网络端口包括ip和端口
IPEndPoint endPoint = new IPEndPoint(address, port1);
//建立连接
_socket1.Connect(endPoint);
while (_socket1.Connected == false)
{
_socket1.Connect(endPoint);
receive_box.Text += ("正在连接");
}
receive_box.Text += ("发送功能连接成功...\r\n");
}
try
{
if(_socket == null)
{
receive_box.Text += ("接收功能未开启,不能发送消息\r\n");
}
if(sendmessage_box.Text == "")
{
return;
}
//向服务器发送消息
_socket1.Send(Encoding.UTF8.GetBytes(user_name + ":" + sendmessage_box.Text));
receive_box.Text += ("\r\n"+user_name+":"+sendmessage_box.Text+"\r\n");
sendmessage_box.Text = "";
}
catch (Exception ex)
{
receive_box.Text += "对方离线....\r\n";
_socket1.Close();
receive_box.Text += (ex.Message);
}
}
}
}
运行效果如下: