我正在尝试使用C#创建异步客户端服务器程序。 我想在没有点击发送按钮的情况下每毫秒向客户端发送数据。我怎样才能做到这一点 ? 单击“发送”按钮后,我的程序已经在客户端和服务器之间发送和接收消息。我想修改这个。
服务器端
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.Net;
using System.Diagnostics;
namespace TCP_Server
{
public partial class ServerForm : Form
{
private Socket _serverSocket;
private Socket _clientSocket;
private byte[] _buffer;
private static int counter = 0;
private Timer timer1;
public ServerForm()
{
string path = @"C:\Users\Busra\Desktop\CommunicationAsyncSocket\CommunicationAsyncSocket\bin\Debug\TCP Client.exe";
Process.Start(path);
InitializeComponent();
StartServer();
}
private void StartServer()
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
_serverSocket.Listen(0);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack),
null);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallBack(IAsyncResult ar)
{
try
{
_clientSocket = _serverSocket.EndAccept(ar);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(RecieveCallBack),null);
AppendToTextBox("Client has connected..");
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RecieveCallBack(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
Array.Resize(ref _buffer, received);
string txt = Encoding.ASCII.GetString(_buffer);
AppendToTextBox(">>Client: "+txt);
Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize);
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendToTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
textBox.Text += " " + text +" "+"\r\n";
});
this.Invoke(invoker);
}
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer2_Tick);
timer1.Interval = 6000000; // in miliseconds
timer1.Start();
}
public void WorkCounter()
{
counter += 10;
textBox_counter.Text = counter + "\r\n";
try
{
byte[] _buffer = Encoding.ASCII.GetBytes(textBox_counter.Text);
_serverSocket.BeginSend(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(SendCallBack), null);
}
catch (SocketException ex)
{ }//server closed
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SendCallBack(IAsyncResult ar)
{
try
{
_serverSocket.EndSend(ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer2_Tick(object sender, EventArgs e)
{
WorkCounter();
}
}
}
客户端
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.Tasks;
using System.Windows.Forms;
namespace CommunicationAsyncSocket
{
public partial class ClientForm : Form
{
private Socket _clientSocket;
private Socket _serverSocket;
private byte[] _buffer;
public ClientForm()
{
InitializeComponent();
}
private void btn_connect_Click(object sender, EventArgs e)
{
try
{
_clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 3333),
new AsyncCallback(ConnectCallBack),null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConnectCallBack(IAsyncResult ar)
{
try
{
_clientSocket.EndConnect(ar);
btn_send.Enabled = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btn_send_Click(object sender, EventArgs e)
{
try
{
byte[] _buffer = Encoding.ASCII.GetBytes(textBox.Text+" "+textBox1.Text);
textBox1.Text = " "; textBox.Text = " ";
_clientSocket.BeginSend(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(SendCallBack), null);
}
catch (SocketException ex)
{ }//server closed
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SendCallBack(IAsyncResult ar)
{
try
{
_clientSocket.EndSend(ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallBack(IAsyncResult ar)
{
try
{
_serverSocket = _clientSocket.EndAccept(ar);
_buffer = new byte[_serverSocket.ReceiveBufferSize];
_serverSocket.BeginReceive(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
AppendToTextBox("Server has connected..");
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RecieveCallBack(IAsyncResult ar)
{
try
{
int received = _serverSocket.EndReceive(ar);
Array.Resize(ref _buffer, received);
string txt = Encoding.ASCII.GetString(_buffer);
AppendToTextBox(">>Server: " + txt);
Array.Resize(ref _buffer, _serverSocket.ReceiveBufferSize);
_serverSocket.BeginReceive(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendToTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
textBoxCounter.Text += " " + text + " " + "\r\n";
});
this.Invoke(invoker);
}
}
}
答案 0 :(得分:0)
在服务器代码中:您使用的计时器应该可以正常工作。但是代码中有一些错误。
InitTimer
函数。所以计时器没有启动。您可能想在调用StartServer
的构造函数中调用它。 timer1.Interval = 6000000;
它的100分钟太长而无法回应。你可能想把它改成6000,即6秒。在WorkCounter
功能更改发送行中
_clientSocket.BeginSend(_buffer, 0,_buffer.Length,SocketFlags.None, new AsyncCallback(SendCallBack), null);
因为您正在客户端套接字上发送数据,所以您应该使用客户端套接字而不是服务器套接字发送它。服务器套接字仅用于列表。客户端套接字用于与客户端进行通信