如何解决如何将多个设备/客户端与服务器连接以及如何与这些连接的设备通信?
实际上我编写了一个代码来与服务器建立多个客户端/设备连接。我的代码与服务器建立了多个连接,并在我选择连接的设备并尝试向客户端发送消息后向我显示已连接的客户端列表,它工作正常,但是当我尝试从客户端接收消息时,它不起作用。>
这是我的代码:
下面的代码与服务器建立了多个客户端/设备连接
private void btnstart_Click(object sender,EventArgs e)
{
string Systemip = getlocalip();
txtinfo.Text = "Server IP:" + Systemip + Environment.NewLine;
var portno = Int32.Parse("8010");
String a = "";
IPAddress ip = IPAddress.Parse(Systemip);
server = new TcpListener(ip,portno);
server.Start();
//here environment.newline means,display msg to next line.
txtinfo.AppendText("Server started waiting for client.............." + Environment.NewLine);
counter = 0;
f = new Form1();
Thread newone = new Thread(loop);
newone.Start();
}
public delegate void messageone();
public void mess()
{
richtxtbddata.AppendText(counter + "clien connected" + Environment.NewLine);
richtxtbddata.AppendText("The client is from IP address: " + ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString() + Environment.NewLine);
// iplist.Items.Add(((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString());
listBox1.Items.Add(counter); //add this (((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString()); on the place of counter
}
public void loop(object obj)
{
connectobj = new List<Multipleconnect>();
while (true)
{
counter++;
socketforclient = server.AcceptSocket();
// ns = new NetworkStream(socketforclient);
connectobj.Add(new Multipleconnect
{
objectno = counter,Skt = socketforclient,nstream = new NetworkStream(socketforclient),ip = ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString()
});
//Box.AppendText(counter + "Client connected");
richtxtbddata.Invoke(new messageone(mess));
Thread UserThread = new Thread(new ThreadStart(() => f.User(socketforclient)));
UserThread.Start();
}
}
public void User(Socket client)
{
while (true)
{
try
{
byte[] msg = new byte[1024];
int size = client.Receive(msg);
client.Send(msg,size,SocketFlags.None);
}
catch (Exception ex)
{
txtinfo.Text = "Divice disconnected";
}
}
}
下面的代码用于发送和接收消息,但在此代码中消息已成功发送到客户端/设备,但此代码未从客户端/设备接收消息。
private void btnsend_Click(object sender,EventArgs e)
{
isNew = true;
if (servermsg.Text != "") {
ns = new NetworkStream(socketforclient);
StreamWriter writer = new StreamWriter(ns);
writer.WriteLine(servermsg.Text + Environment.NewLine);
txtinfo.AppendText("Server:" + servermsg.Text + Environment.NewLine);
writer.Flush();
writer.Close();
}
ns = new NetworkStream(socketforclient);
StreamReader sr = new StreamReader(ns);
string myCompleteMessage = string.Empty;
if (ns.DataAvailable)
{
myReadBuffer = new byte[2048];
datafinal = new double[1];
myCompleteMessage = Encoding.ASCII.GetString(myReadBuffer,readbytes);
}
//runn();
if (myCompleteMessage != "")
{
txtinfo.AppendText("Client:" + myCompleteMessage + Environment.NewLine + Environment.NewLine);
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
/// <summary>
/// single connection in working condition with old code.....
/// </summary>
namespace TcpsERVER
{
public partial class Form1 : Form
{
List<Multipleconnect> connectobj;
Form1 f;
int counter = 0;
NetworkStream ns;
int i = 0;
Socket socketforclient;
TcpListener server;
byte[] myReadBuffer;
int readbytes;
int p = 0;
int y;
double[] datafinal;
double[] yy;
List<double> xx;
string stop = "";
Multipleconnect mulcon = new Multipleconnect();
public Form1()
{
InitializeComponent();
//txtserverip.Text = getlocalip();
Featuresduringrun();
// Connnection();
}
private void btnstart_Click(object sender,EventArgs e)
{
string Systemip = getlocalip();
txtinfo.Text = "Server IP:" + Systemip + Environment.NewLine;
var portno = Int32.Parse("8010");
String a = "";
IPAddress ip = IPAddress.Parse(Systemip);
server = new TcpListener(ip,portno);
server.Start();
//here environment.newline means,display msg to next line.
txtinfo.AppendText("Server started waiting for client.............." + Environment.NewLine);
counter = 0;
f = new Form1();
Thread newone = new Thread(loop);
newone.Start();
}
public delegate void messageone();
public void mess()
{
richtxtbddata.AppendText(counter + "clien connected" + Environment.NewLine);
richtxtbddata.AppendText("The client is from IP address: " + ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString() + Environment.NewLine);
// iplist.Items.Add(((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString());
listBox1.Items.Add(counter); //add this (((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString()); on the place of counter
}
public void loop(object obj)
{
connectobj = new List<Multipleconnect>();
while (true)
{
counter++;
socketforclient = server.AcceptSocket();
// ns = new NetworkStream(socketforclient);
connectobj.Add(new Multipleconnect
{
objectno = counter,ip = ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString()
});
//Box.AppendText(counter + "Client connected");
richtxtbddata.Invoke(new messageone(mess));
Thread UserThread = new Thread(new ThreadStart(() => f.User(socketforclient)));
UserThread.Start();
}
}
public void User(Socket client)
{
while (true)
{
try
{
byte[] msg = new byte[1024];
int size = client.Receive(msg);
client.Send(msg,SocketFlags.None);
}
catch (Exception ex)
{
txtinfo.Text = "Divice disconnected";
}
}
}
public static string getlocalip()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach(var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "not found any ip";
}
private void btnsend_Click(object sender,EventArgs e)
{
string aa = listBox1.SelectedItems[0].ToString();
if (aa == null)
{
MessageBox.Show("Selexct a item");
}
if (servermsg.Text != "") {
ns = new NetworkStream(socketforclient);
StreamWriter writer = new StreamWriter(ns);
writer.WriteLine(servermsg.Text + Environment.NewLine);
txtinfo.AppendText("Server:" + servermsg.Text + Environment.NewLine);
writer.Flush();
writer.Close();
}
ns = new NetworkStream(socketforclient);
StreamReader sr = new StreamReader(ns);
string myCompleteMessage = string.Empty;
if (ns.DataAvailable)
{
myReadBuffer = new byte[2062];
int rreadbytes = ns.Read(myReadBuffer,myReadBuffer.Length);
string Client2 = Encoding.ASCII.GetString(myReadBuffer,rreadbytes);
myCompleteMessage = Client2;
}
if (myCompleteMessage != "")
{
txtinfo.AppendText("Client:" + myCompleteMessage + Environment.NewLine + Environment.NewLine);
}
}
private Form activeform = null;
private void listBox1_SelectedindexChanged(object sender,EventArgs e)
{
string aa = listBox1.SelectedItems[0].ToString();
if (aa == null)
{
MessageBox.Show("Selexct a item");
}
//// int endindex = aa.Length - 1;
//// int b = aa.IndexOf("}");
////aa = aa.Substring(15,13);
foreach (var ob in connectobj)
{
if (ob.objectno.ToString() == aa) //write ob.ip on the place of ob.objectno
{
socketforclient = ob.Skt;
MessageBox.Show("yes");
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.sockets;
using System.Text;
using System.Threading.Tasks;
namespace TcpsERVER
{
class Multipleconnect
{
public int objectno;
public Socket Skt;
public string ip;
public NetworkStream nstream;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。