C# 从.net套接字中的无限循环获取变量
我正在使用.NET同步套接字将数据从客户端发送到服务器 我需要从C# 从.net套接字中的无限循环获取变量,c#,.net,visual-studio-2010,sockets,C#,.net,Visual Studio 2010,Sockets,我正在使用.NET同步套接字将数据从客户端发送到服务器 我需要从StartListening()方法中获取数据,以便在Main()中使用它 变量数据位于无限循环中(while(true))。 需要帮忙吗 这是服务器代码: using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; public class SynchronousSocketListen
StartListening()
方法中获取数据,以便在Main()中使用它
变量数据位于无限循环中(while(true))
。
需要帮忙吗
这是服务器代码:
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo;
IPAddress ipAddress ;
IPEndPoint localEndPoint;
Socket listener;
// Incoming data from the client.
public static string data = null;
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
public void InitializeListening()
{
// Data buffer for incoming data.
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
ipHostInfo = Dns.Resolve("localhost");
ipAddress = ipHostInfo.AddressList[0];
localEndPoint = new IPEndPoint(ipAddress, 11007);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
}
public void StopListening()
{
_shouldStop = true;
byte[] msg = Encoding.ASCII.GetBytes("please stop!");
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(localEndPoint);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
public void StartListening()
{
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Thread is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
// An incoming connection needs to be processed.
if (_shouldStop)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
break;
}
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
byte[] msg = Encoding.ASCII.GetBytes("Salam !");
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
Console.WriteLine("I am the Synchronous Socket Server\n");
SynchronousSocketListener pServer = new SynchronousSocketListener();
pServer.InitializeListening();
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
Console.WriteLine("listening thread sevice started...\n");
Console.WriteLine("\nPress Q when you want to quit...\n");
int car;
do
{
Thread.Sleep(100);
car = Console.Read();
if (car == 81)
{
// Request that the worker thread stop itself:
pServer.StopListening();
// Use the Join method to block the current process
// until the object's thread terminates.
serverkerThread.Join();
break;
}
} while (true);
Console.WriteLine("listening thread sevice stopped and program will be exited...\n");
return 0;
}
}
使用系统;
使用系统线程;
Net系统;
使用System.Net.Sockets;
使用系统文本;
公共类SynchronousSocketListener
{
字节[]字节=新字节[1024];
IPHostEntry-ipHostInfo;
IPAddress-IPAddress;
IPEndPoint本地端点;
套接字侦听器;
//来自客户端的传入数据。
公共静态字符串数据=null;
//Volatile用于向编译器提示此数据
//成员将由多个线程访问。
私人的不稳定行为应该停止;
public void InitializeListening()
{
//输入数据的数据缓冲区。
//为套接字建立本地端点。
//Dns.GetHostName返回
//运行应用程序的主机。
ipHostInfo=Dns.Resolve(“localhost”);
ipAddress=ipHostInfo.AddressList[0];
localEndPoint=新的IPEndPoint(ipAddress,11007);
//创建TCP/IP套接字。
侦听器=新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
Bind(localEndPoint);
听(10);
}
公营部门
{
_shouldStop=true;
byte[]msg=Encoding.ASCII.GetBytes(“请停止!”);
//创建TCP/IP套接字。
套接字发送器=新套接字(AddressFamily.InterNetwork,
流,ProtocolType.Tcp);
//将套接字连接到远程终结点。捕获所有错误。
试一试{
sender.Connect(localEndPoint);
//通过套接字发送数据。
int bytesent=sender.Send(msg);
//松开插座。
发送器关闭(SocketShutdown.Both);
sender.Close();
}
捕集物(捕集物)
{
WriteLine(“ArgumentNullException:{0}”,ane.ToString());
}
捕获(SocketException se)
{
WriteLine(“SocketException:{0}”,se.ToString());
}
捕获(例外e)
{
WriteLine(“意外异常:{0}”,e.ToString());
}
}
公营机构
{
//将套接字绑定到本地端点并
//侦听传入的连接。
尝试
{
//开始监听连接。
while(true)
{
Console.WriteLine(“等待连接…”);
//线程在等待传入连接时挂起。
套接字处理程序=listener.Accept();
//需要处理传入连接。
如果(你应该停止)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
打破
}
数据=空;
while(true)
{
字节=新字节[1024];
int bytesRec=handler.Receive(字节);
data+=Encoding.ASCII.GetString(字节,0,bytesRec);
if(data.IndexOf(“”>-1)
{
打破
}
}
//在控制台上显示数据。
WriteLine(“接收到的文本:{0}”,数据);
//将数据回显到客户端。
//byte[]msg=Encoding.ASCII.GetBytes(数据);
byte[]msg=Encoding.ASCII.GetBytes(“Salam!”);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
公共静态int Main(字符串[]args)
{
WriteLine(“我是同步套接字服务器\n”);
SynchronousSocketListener pServer=新的SynchronousSocketListener();
pServer.InitializeListening();
线程serverkerThread=新线程(pServer.StartListening);
serverkerThread.Start();
//循环,直到服务器线程激活。
而(!serverkerThread.IsAlive);
Console.WriteLine(“侦听线程服务已启动…\n”);
Console.WriteLine(“\n要退出时按Q…\n”);
int轿车;
做
{
睡眠(100);
car=控制台。读取();
如果(car==81)
{
//请求工作线程停止自身:
pServer.StopListening();
//使用Join方法阻止当前进程
//直到对象的线程终止。
serverkerThread.Join();
打破
}
}虽然(正确);
Console.WriteLine(“侦听线程服务已停止,程序将退出…\n”);
返回0;
}
}
收到的数据(假定是以“EOF”结尾的ASCII字符串)存储在pServer对象的名为“data”的公共成员中,您可以如下方式访问它:
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
string receivedString = pServer.data; // <<--- here we get the received string
Console.WriteLine("listening thread sevice started...\n");
Thread serverkerThread=新线程(pServer.StartListening);
serverkerThread.Start();
//循环,直到服务器线程激活。
而(!serverkerThread.IsAlive);
字符串receivedString=pServer.data;//由于您的成员数据
是静态的,您可以从类中的任何位置访问它。我只想知道两件事:为什么要使用同步套接字(因为阻塞套接字通常更容易、更有效