开始和Asynccallback循环
我正在尝试仅使用一台服务器和多个客户端进行聊天应用程序。我正在尝试将客户端的部分放在循环中,但是当我将其放在循环中时,它会产生连接错误。虽然,就像我想要的那样,消息发送给所有客户。你们能帮我吗?我是TCP的新手,所以我不太了解。
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;
using System.Net.Sockets;
namespace ChessClient
{
public partial class Form1 : Form
{
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
private System.Windows.Forms.Timer timer1;
private int counter = 180;
public Form1()
{
InitializeComponent();
sendbtn.Click += new EventHandler(ButtonSendOnClick);
connectbtn.Click += new EventHandler(ButtonConnectOnClick);
disconnectbtn.Click += new EventHandler(ButtonDisconOnClick);
}
void ButtonConnectOnClick(object obj, EventArgs ea)
{
conStatus.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
void ButtonSendOnClick(object obj, EventArgs ea)
{
byte[] message = Encoding.ASCII.GetBytes(chat.Text);
chat.Clear();
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void ButtonDisconOnClick(object obj, EventArgs ea)
{
client.Close();
conStatus.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
这个我希望它在循环中的地方
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
catch (SocketException)
{
conStatus.Text = "Error connecting";
}
}
void ReceiveData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
chatBox.Text += stringData;
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
private void btnStart_Click_1(object sender, EventArgs e)
{
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
countDownLabel.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
timer1.Stop();
countDownLabel.Text = counter.ToString();
}
}
}
下面的代码是服务器部分。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class newClient
{
public Socket newServerSocket;
public newClient(Socket client)
{
this.newServerSocket = client;
}
public void speakToClient()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint clientep = (IPEndPoint)newServerSocket.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
newServerSocket.Send(data, data.Length, SocketFlags.None);
while (true)
{
data = new byte[1024];
recv = newServerSocket.Receive(data);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
foreach(Socket socket in SimpleTcpSrvr.Clients)
{
socket.Send(data, recv, SocketFlags.None);
}
}
newServerSocket.Close();
}
}
class SimpleTcpSrvr
{
public static List<Socket> Clients = new List<Socket>();
public static void Main()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9060);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
while (true)
{
Socket client = newsock.Accept();
Clients.Add(client);
newClient threadClient = new newClient(client);
Thread newthread = new Thread(new ThreadStart(threadClient.speakToClient));
newthread.Start();
}
}
}
I am trying to make a chat application with only one server and more than one clients. I am trying to put client.BeginReceive part in a loop but when i put it in a loop it gives connection errors. Although, just as i wanted, message is sent to all clients. Can you guys help me about this? I am new to TCP so I don't know much.
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;
using System.Net.Sockets;
namespace ChessClient
{
public partial class Form1 : Form
{
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
private System.Windows.Forms.Timer timer1;
private int counter = 180;
public Form1()
{
InitializeComponent();
sendbtn.Click += new EventHandler(ButtonSendOnClick);
connectbtn.Click += new EventHandler(ButtonConnectOnClick);
disconnectbtn.Click += new EventHandler(ButtonDisconOnClick);
}
void ButtonConnectOnClick(object obj, EventArgs ea)
{
conStatus.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
void ButtonSendOnClick(object obj, EventArgs ea)
{
byte[] message = Encoding.ASCII.GetBytes(chat.Text);
chat.Clear();
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void ButtonDisconOnClick(object obj, EventArgs ea)
{
client.Close();
conStatus.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
This where i want it to be in a loop
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
catch (SocketException)
{
conStatus.Text = "Error connecting";
}
}
void ReceiveData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
chatBox.Text += stringData;
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
private void btnStart_Click_1(object sender, EventArgs e)
{
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
countDownLabel.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
timer1.Stop();
countDownLabel.Text = counter.ToString();
}
}
}
The code below is the server part.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class newClient
{
public Socket newServerSocket;
public newClient(Socket client)
{
this.newServerSocket = client;
}
public void speakToClient()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint clientep = (IPEndPoint)newServerSocket.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
newServerSocket.Send(data, data.Length, SocketFlags.None);
while (true)
{
data = new byte[1024];
recv = newServerSocket.Receive(data);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
foreach(Socket socket in SimpleTcpSrvr.Clients)
{
socket.Send(data, recv, SocketFlags.None);
}
}
newServerSocket.Close();
}
}
class SimpleTcpSrvr
{
public static List<Socket> Clients = new List<Socket>();
public static void Main()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9060);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
while (true)
{
Socket client = newsock.Accept();
Clients.Add(client);
newClient threadClient = new newClient(client);
Thread newthread = new Thread(new ThreadStart(threadClient.speakToClient));
newthread.Start();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论