无法连接c#中的2台计算机

时间:2012-11-15 10:52:44

标签: c# .net sockets networking network-programming

我正在尝试在两台计算机之间发送消息。我已经能够建立连接,但由于一些奇怪的原因,我无法获得流。

服务器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace chat_server
{
 class Program
 {
    static void Main(string[] args)
    {
        TcpListener server = new TcpListener(IPAddress.Any, 9999);
        server.Start();

        Console.WriteLine("Waiting for client connections");
        TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Client request accepted");

        NetworkStream stream = client.GetStream();
        StreamReader reader = new StreamReader(stream);
        StreamWriter writer = new StreamWriter(stream);

        Console.WriteLine("The message is " + reader.ReadToEnd());
    }
 }
}

客户代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace chat_client
{
 class Program
 {
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient("localhost", 9999);

        NetworkStream stream = client.GetStream();
        StreamReader reader = new StreamReader(stream);
        StreamWriter writer = new StreamWriter(stream);

        writer.Write("Hello world");
        Console.WriteLine("Message Sent");
        Console.ReadKey();
    }
 }
}

我的服务器代码通过打印接受的客户端请求来确认客户端连接。但由于某种原因,我无法从流中获取数据。快速帮助将非常感激。

谢谢

2 个答案:

答案 0 :(得分:3)

您需要刷新流才能实际发送数据。

尝试:

writer.Write("Hello world");
writer.Flush();

有关详细信息,请查看MSDN文档:

同步套接字服务器:http://msdn.microsoft.com/en-us/library/6y0e13d3.aspx 异步套接字服务器:http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx

这是一个网站,更详细地解释了套接字的来龙去脉:http://nitoprograms.blogspot.co.uk/2009/04/tcpip-net-sockets-faq.html

答案 1 :(得分:0)

在服务器端,

在顶部添加static TcpListener server;

然后`server.Start();

        Socket soc = listener.AcceptSocket();

        Console.WriteLine("Connection successful");
        Stream s = new NetworkStream(soc);

        StreamReader reader = new StreamReader(s);
        StreamWriter writer= new StreamWriter(s);

        sw.AutoFlush = true;
        sw.WriteLine("hello world");`

在客户端

 TcpClient client = new TcpClient("localhost", 9999);
        Stream s = client.GetStream();
        Console.WriteLine("Connection successfully received");

        StreamWriter writer = new StreamWriter(s);
        StreamReader reader = new StreamReader(s);
        sw.AutoFlush = true;
        string dis=reader.readLine();
        Console.WriteLine(dis); 

希望它现在可以运作。