日期:2014-05-19  浏览次数:20855 次

端口局域网内远程通讯问题
1。我在局域网的服务器上安装了一个服务,这个服务的功能是监听5678端口,并发送字节;

public   void   Start()
{
ReadQuotes();
listenerThread   =   new   Thread(
new   ThreadStart(this.Listener));
listenerThread.Start();
}
protected   void   Listener()
{
try
{
//IPAddress   ipAddress   =   Dns.Resolve( "localhost ").AddressList[0];
                                IPAddress   ipAddress   =   IPAddress.Parse( "192.168.0.3 ");
listener   =   new   TcpListener(ipAddress,   port);
listener.Start();  
while   (true)
{
Socket   socket   =   listener.AcceptSocket();
string   message   =   GetRandomQuoteOfTheDay();
UnicodeEncoding   encoder   =   new   UnicodeEncoding();
byte[]   buffer   =   encoder.GetBytes(message);
socket.Send(buffer,   buffer.Length,   0);
socket.Close();

                                        //performanceCounterRequestsTotal.Increment();
                                        //performanceCounterBytesSentTotal.IncrementBy(buffer.Length);

                                        //requestsPerSec++;
                                        //bytesPerSec   +=   buffer.Length;
}
}
catch   (SocketException   e)
{
string   message   =   "Quote   Server   failed   in   Listener:   "  
+   e.Message;
eventLog.WriteEntry(message,   EventLogEntryType.Error);
}
}
public   void   Stop()
{
listener.Stop();
}
public   void   Suspend()
{
listenerThread.Suspend();
}
public   void   Resume()
{
listenerThread.Resume();
}
2。同时我又做了一个客户端UI程序去读取服务器端发送的内容。
private   void   buttonQuote_Click(object   sender,   System.EventArgs   e)
{
statusBar.Text   =   " ";
string   server   =   textHostname.Text;
try
{
int   port   =   Convert.ToInt32(textPortNumber.Text);
}
catch   (FormatException   ex)
{
statusBar.Text   =   ex.Message;
return;
}
TcpClient   client   =   new   TcpClient();
try
{
client.Connect(textHostname.Text,
Convert.ToInt32(textPortNumber.Text));
NetworkStream   stream   =   client.GetStream();
byte[]   buffer   =   new   Byte[1024];
int   received   =   stream.Read(buffer,   0,   1024);
if   (received   <=   0)
{
statusBar.Text   =   "Read   failed ";
return;
}
textQuote.Text   = &nbs