0

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

服务器代码

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();
    }
 }
}

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

谢谢

4

2 回答 2

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

于 2012-11-15T10:54:06.257 回答
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); 

希望它现在可以工作。

于 2012-11-15T11:16:12.500 回答