TCP客户端:不允许在未连接的套接字上进行操作-C#4.5

TCP客户端:不允许在未连接的套接字上进行操作-C#4.5,c#,tcp,client-server,tcpclient,C#,Tcp,Client Server,Tcpclient,为什么下面的代码会给出以下异常 不允许在未连接的插座上进行操作。 他说: 您必须Connect()才能获得NetworkStream 对于这类东西,文档通常是非常好的。在下面 异常在GetStream的帮助中,您将看到: InvalidOperationException:TcpClient未连接到远程主机 在这里,我的客户也在做同样的事情 那么,出了什么问题 客户端代码: using System; using System.Net.Sockets; using System.IO; na

为什么下面的代码会给出以下异常

不允许在未连接的插座上进行操作。

他说:

您必须
Connect()
才能获得
NetworkStream

对于这类东西,文档通常是非常好的。在下面 异常在
GetStream
的帮助中,您将看到:

InvalidOperationException
TcpClient
未连接到远程主机

在这里,我的客户也在做同样的事情

那么,出了什么问题

客户端代码:

using System;
using System.Net.Sockets;
using System.IO;

namespace WhoIsClientNamespace
{
    public class WhoIsClient
    {
        static void Main()
        {
            Console.Title = "Client";
            string kbInput;
            try
            {
                TcpClient client = new TcpClient();
                client.Connect("localHost", 43);
                Console.WriteLine("Client started...");
                Console.WriteLine("Enter command to the server!");
                Console.WriteLine(" # ");

                while (true)
                {
                    kbInput = Console.ReadLine();
                    Console.WriteLine(kbInput);

                    if ("exit" == kbInput)
                    {
                        Console.WriteLine("while loop exited!");
                        break;
                    }

                    string[] args = kbInput.Split(' ');

                    if (args.Length < 1)
                    {
                        Console.WriteLine("Provide more than one Args");
                    }
                    else if (args.Length == 1)
                    {
                        StreamWriter sw = new StreamWriter(client.GetStream());
                        StreamReader sr = new StreamReader(client.GetStream());
                        string str = kbInput;
                        sw.WriteLine(kbInput);
                        sw.Flush();
                        Console.WriteLine(kbInput[0] + " is " + sr.ReadToEnd());
                        return;
                    }
                    else if (args.Length > 1)
                    {
                        StreamWriter sw = new StreamWriter(client.GetStream());
                        StreamReader sr = new StreamReader(client.GetStream());
                        string str = kbInput;
                        sw.WriteLine(str);
                        sw.Flush();
                        //Console.WriteLine(kbInput[0] + " location changed to be " + args[1]);
                        sw.Close();
                    }
                    else
                    {
                        Console.WriteLine("Invalid args ");
                    }
                }                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Client exits!");
        }
    }
}
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;

namespace WhoIsServerNamespace
{
    public class WhoIsServer
    {
        static Dictionary<string, string> 
            _locationsDictionary = new Dictionary<String, String>();
        static void Main(string[] args)
        {
            Console.Title = "Server";
            runServer();
        }
        static void runServer()
        {
            TcpListener listener;
            Socket connection;
            NetworkStream socketStream;
            try
            {
                listener = new TcpListener(IPAddress.Any, 43);
                listener.Start();

                Console.WriteLine("server started listening");

                while (true)
                {
                    connection = listener.AcceptSocket();
                    socketStream = new NetworkStream(connection);
                    Console.WriteLine("Connection Received");
                    doRequest(socketStream);
                    socketStream.Close();
                    connection.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception:" + e.ToString());
            }
        }

        static void doRequest(NetworkStream socketStream)
        {
            try
            {
                StreamWriter sw = new StreamWriter(socketStream);
                StreamReader sr = new StreamReader(socketStream);
                String strClientInput = sr.ReadLine();
                Console.WriteLine("Respond Received:" + strClientInput);
                String[] clientInputsSplitted = strClientInput.Split(new char[] { ' ' }, 2);
                String name;
                String location;

                if (clientInputsSplitted.Length < 1)
                {
                    Console.WriteLine("Too little words was inputted");
                }
                else if (clientInputsSplitted.Length == 1)
                {/* when we receive only one command-string from client,
                    that is considered as the name of the server.
                    So, the server returns its corresponding location. */
                    name = clientInputsSplitted[0];//obtain the name from the client-command-string.
                    if (_locationsDictionary.ContainsKey(name))//Is the [name] in the dictionary?
                    {
                        Console.WriteLine(name + "'s location is :"+ _locationsDictionary[name]);
                        sw.WriteLine(_locationsDictionary[name]);//return location to the client.
                    }
                    else
                    {
                        Console.WriteLine("Error: [name] not found in the dictionary");
                        sw.WriteLine("Error: [name] not found in the dictionary");
                    }
                    sw.Flush();
                }
                else if (clientInputsSplitted.Length == 2)
                {/* when we receive two command-string from client,
                    that is considered as the (name, location) pair of the server.
                    So, the server returns its corresponding location. */
                    name = clientInputsSplitted[0];
                    location = clientInputsSplitted[1];

                    if (_locationsDictionary.ContainsKey(name))
                    {
                        _locationsDictionary[name] = location;
                        Console.WriteLine("(" + name + "," + location + ") updated");
                        sw.WriteLine("("+name +","+ location +") updated");
                    }
                    else
                    {
                        _locationsDictionary.Add(name, location);
                        Console.WriteLine("(" + name + "," + location + ") added");
                        sw.WriteLine("(" + name + "," + location + ") added");
                    }
                    sw.Flush();
                }

                if (strClientInput.Contains("-h0"))
                {
                    Console.WriteLine("Is                ok");
                    sw.WriteLine("Is ok");
                }
                else if (strClientInput.Contains("-h9"))
                {
                    Console.WriteLine("Hey you're progressing");
                    sw.WriteLine("Hey you're progressing");
                }
                else if (strClientInput.Contains("-h1"))
                {
                    Console.WriteLine("We're Done");
                    sw.WriteLine("We're Done");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong");
                Console.WriteLine(e.Message);
            }
        }
    }
}
使用系统;
使用System.Net.Sockets;
使用System.IO;
命名空间WhoIsClientNamespace
{
公共类WhoIsClient
{
静态void Main()
{
Console.Title=“客户端”;
字符串输入;
尝试
{
TcpClient client=新的TcpClient();
client.Connect(“localHost”,43);
Console.WriteLine(“客户端已启动…”);
WriteLine(“向服务器输入命令!”);
Console.WriteLine(“#”);
while(true)
{
kbInput=Console.ReadLine();
控制台写入线(kbInput);
如果(“退出”==kbInput)
{
WriteLine(“当循环退出时!”);
打破
}
字符串[]args=kbInput.Split(“”);
如果(参数长度<1)
{
Console.WriteLine(“提供多个参数”);
}
else if(args.Length==1)
{
StreamWriter sw=新的StreamWriter(client.GetStream());
StreamReader sr=新的StreamReader(client.GetStream());
字符串str=kbInput;
软件写入线(kbInput);
sw.Flush();
Console.WriteLine(kbInput[0]+“是”+sr.ReadToEnd());
回来
}
否则如果(args.Length>1)
{
StreamWriter sw=新的StreamWriter(client.GetStream());
StreamReader sr=新的StreamReader(client.GetStream());
字符串str=kbInput;
sw.WriteLine(str);
sw.Flush();
//Console.WriteLine(kbInput[0]+“位置更改为”+args[1]);
sw.Close();
}
其他的
{
Console.WriteLine(“无效参数”);
}
}                
}
捕获(例外e)
{
控制台写入线(e.Message);
}
Console.WriteLine(“客户端退出!”);
}
}
}
服务器代码:

using System;
using System.Net.Sockets;
using System.IO;

namespace WhoIsClientNamespace
{
    public class WhoIsClient
    {
        static void Main()
        {
            Console.Title = "Client";
            string kbInput;
            try
            {
                TcpClient client = new TcpClient();
                client.Connect("localHost", 43);
                Console.WriteLine("Client started...");
                Console.WriteLine("Enter command to the server!");
                Console.WriteLine(" # ");

                while (true)
                {
                    kbInput = Console.ReadLine();
                    Console.WriteLine(kbInput);

                    if ("exit" == kbInput)
                    {
                        Console.WriteLine("while loop exited!");
                        break;
                    }

                    string[] args = kbInput.Split(' ');

                    if (args.Length < 1)
                    {
                        Console.WriteLine("Provide more than one Args");
                    }
                    else if (args.Length == 1)
                    {
                        StreamWriter sw = new StreamWriter(client.GetStream());
                        StreamReader sr = new StreamReader(client.GetStream());
                        string str = kbInput;
                        sw.WriteLine(kbInput);
                        sw.Flush();
                        Console.WriteLine(kbInput[0] + " is " + sr.ReadToEnd());
                        return;
                    }
                    else if (args.Length > 1)
                    {
                        StreamWriter sw = new StreamWriter(client.GetStream());
                        StreamReader sr = new StreamReader(client.GetStream());
                        string str = kbInput;
                        sw.WriteLine(str);
                        sw.Flush();
                        //Console.WriteLine(kbInput[0] + " location changed to be " + args[1]);
                        sw.Close();
                    }
                    else
                    {
                        Console.WriteLine("Invalid args ");
                    }
                }                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Client exits!");
        }
    }
}
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;

namespace WhoIsServerNamespace
{
    public class WhoIsServer
    {
        static Dictionary<string, string> 
            _locationsDictionary = new Dictionary<String, String>();
        static void Main(string[] args)
        {
            Console.Title = "Server";
            runServer();
        }
        static void runServer()
        {
            TcpListener listener;
            Socket connection;
            NetworkStream socketStream;
            try
            {
                listener = new TcpListener(IPAddress.Any, 43);
                listener.Start();

                Console.WriteLine("server started listening");

                while (true)
                {
                    connection = listener.AcceptSocket();
                    socketStream = new NetworkStream(connection);
                    Console.WriteLine("Connection Received");
                    doRequest(socketStream);
                    socketStream.Close();
                    connection.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception:" + e.ToString());
            }
        }

        static void doRequest(NetworkStream socketStream)
        {
            try
            {
                StreamWriter sw = new StreamWriter(socketStream);
                StreamReader sr = new StreamReader(socketStream);
                String strClientInput = sr.ReadLine();
                Console.WriteLine("Respond Received:" + strClientInput);
                String[] clientInputsSplitted = strClientInput.Split(new char[] { ' ' }, 2);
                String name;
                String location;

                if (clientInputsSplitted.Length < 1)
                {
                    Console.WriteLine("Too little words was inputted");
                }
                else if (clientInputsSplitted.Length == 1)
                {/* when we receive only one command-string from client,
                    that is considered as the name of the server.
                    So, the server returns its corresponding location. */
                    name = clientInputsSplitted[0];//obtain the name from the client-command-string.
                    if (_locationsDictionary.ContainsKey(name))//Is the [name] in the dictionary?
                    {
                        Console.WriteLine(name + "'s location is :"+ _locationsDictionary[name]);
                        sw.WriteLine(_locationsDictionary[name]);//return location to the client.
                    }
                    else
                    {
                        Console.WriteLine("Error: [name] not found in the dictionary");
                        sw.WriteLine("Error: [name] not found in the dictionary");
                    }
                    sw.Flush();
                }
                else if (clientInputsSplitted.Length == 2)
                {/* when we receive two command-string from client,
                    that is considered as the (name, location) pair of the server.
                    So, the server returns its corresponding location. */
                    name = clientInputsSplitted[0];
                    location = clientInputsSplitted[1];

                    if (_locationsDictionary.ContainsKey(name))
                    {
                        _locationsDictionary[name] = location;
                        Console.WriteLine("(" + name + "," + location + ") updated");
                        sw.WriteLine("("+name +","+ location +") updated");
                    }
                    else
                    {
                        _locationsDictionary.Add(name, location);
                        Console.WriteLine("(" + name + "," + location + ") added");
                        sw.WriteLine("(" + name + "," + location + ") added");
                    }
                    sw.Flush();
                }

                if (strClientInput.Contains("-h0"))
                {
                    Console.WriteLine("Is                ok");
                    sw.WriteLine("Is ok");
                }
                else if (strClientInput.Contains("-h9"))
                {
                    Console.WriteLine("Hey you're progressing");
                    sw.WriteLine("Hey you're progressing");
                }
                else if (strClientInput.Contains("-h1"))
                {
                    Console.WriteLine("We're Done");
                    sw.WriteLine("We're Done");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong");
                Console.WriteLine(e.Message);
            }
        }
    }
}
使用系统;
Net系统;
使用System.Net.Sockets;
使用System.IO;
使用System.Collections.Generic;
命名空间WhoIsServerNamespace
{
公共类WhoIsServer
{
静态词典
_locationsDictionary=新字典();
静态void Main(字符串[]参数)
{
Console.Title=“服务器”;
runServer();
}
静态void runServer()
{
听者;
插座连接;
网络流socketStream;
尝试
{
侦听器=新的TcpListener(IPAddress.Any,43);
listener.Start();
WriteLine(“服务器开始侦听”);
while(true)
{
connection=listener.AcceptSocket();
socketStream=新网络流(连接);
Console.WriteLine(“接收到连接”);
doRequest(socketStream);
socketStream.Close();
connection.Close();
}
}
捕获(例外e)
{
Console.WriteLine(“异常:+e.ToString());
}
}
静态void doRequest(NetworkStream socketStream)
{
尝试
{
StreamWriter sw=新StreamWriter(socketStream);
StreamReader sr=新的StreamReader(socketStream);
字符串strClientInput=sr.ReadLine();
Console.WriteLine(“接收到响应:+strClientInput”);
字符串[]clientInputsSplited=strClientInput.Split(新字符[]{''},2);
字符串名;
字符串位置;
if(clientInputsSplited.Length<1)
{
Console.WriteLine(“输入的字太少”);
}
else if(clientInputsSplited.Length==1)
{/*当我们从客户端只收到一个命令字符串时,
这被视为服务器的名称。
因此,服务器返回其相应的位置*/
name=clientInputsSplited[0];//从客户端命令字符串获取名称。
if(_locationsDictionary.ContainsKey(name))//是字典中的[name]吗?
{
WriteLine(name+“)的位置是:“+\u locationsDictionary[name]);
sw.WriteLine(_locationsDictionary[name]);//将位置返回给客户端。
}
其他的
{
Console.WriteLine(“字典中找不到错误:[名称]);
sw.WriteLine(“错误:[名称