我在c#中创建了一个简单的服务器和客户端程序。服务器将发送一个字符串数组给客户端,客户端将显示它,客户端将向服务器发送一个id,服务器将显示它。我的示例代码如下。当我运行它们时,服务器端出现异常。我已标记在我收到exception.My示例代码如下一行:在c#套接字中从服务器获取异常
服务器:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace server
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpClient.GetStream();
string[] arr1 = new string[] { "one", "two", "three" };
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream(), arr1);
tcpClient.Close();
int recv = ns.Read(data, 0, data.Length); //getting exception in this line
string id = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(id);
}
}
}
}
客户端:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace Client
{
class Program
{
static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
string stringData;
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
NetworkStream ns = tcpClient.GetStream();
var serializer = new XmlSerializer(typeof(string[]));
var stringArr = (string[])serializer.Deserialize(tcpClient.GetStream());
foreach (string s in stringArr)
{
Console.WriteLine(s);
}
string input = Console.ReadLine();
ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
ns.Flush();
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.Read();
}
}
}
我得到的例外是:
An unhandled exception of type 'System.ObjectDisposedException' occurred in System.dll
Additional information: Cannot access a disposed object.
代码中有什么问题吗?我需要做什么来避免这种异常?
谢谢。有用 !!! – ACE
另外一件事:如果我添加StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());在客户端和StreamReader的结尾处reader1 = new StreamReader(tcpClient.GetStream()); 在你的给定代码的最后一行后面的服务器末尾,我在这条线上的服务器上收到一个异常。其实我试图发送文件名和文件大小从客户端到服务器,这就是为什么加入这一行。这里有什么不对吗?@Yacoub Massad – ACE
我不确定。我不认为你应该有两个阅读器('BinaryReader'和'StreamReader')。你为什么需要这样做?使用'BinaryWriter'和'BinaryReader'。您可以使用这些对象将文件大小写入/读取为整数。另外,'BinaryWriter'有一个[overload](https://msdn.microsoft.com/en-us/library/ms143302(v = vs.110).aspx),允许你写byte []。用它来发送文件的内容。 'BinaryReader'具有相应的[重载](https://msdn.microsoft.com/en-us/library/ms143295(v = vs.110).aspx),它允许您读取二进制数据。 –