一尘不染

无法建立连接,因为目标计算机主动拒绝它127.0.0.1:3446

c#

我使用的是WCF4.0模板-
REST。我正在尝试一种使用流上传文件的方法。

问题总是发生在

Stream serverStream = request.GetRequestStream();

流类:

namespace LogicClass
{
    public class StreamClass : IStreamClass
    {
        public bool UploadFile(string filename, Stream fileStream)
        {
            try
            {
                FileStream fileToupload = new FileStream(filename, FileMode.Create);
                byte[] bytearray = new byte[10000];
                int bytesRead, totalBytesRead = 0;
                do
                {
                    bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
                    totalBytesRead += bytesRead;
                } while (bytesRead > 0);

                fileToupload.Write(bytearray, 0, bytearray.Length);
                fileToupload.Close();
                fileToupload.Dispose();
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
            return true;
        }
    }
}

REST项目:

[WebInvoke(UriTemplate = "AddStream/{filename}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStream(string filename, System.IO.Stream fileStream)
{
    LogicClass.FileComponent rest = new LogicClass.FileComponent();
    return rest.AddStream(filename, fileStream);
}

Windows Form项目:用于测试

private void button24_Click(object sender, EventArgs e)
{
    byte[] fileStream;
    using (FileStream fs = new FileStream("E:\\stream.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        fileStream = new byte[fs.Length];
        fs.Read(fileStream, 0, (int)fs.Length);
        fs.Close();
        fs.Dispose();
    }

    string baseAddress = "http://localhost:3446/File/AddStream/stream.txt";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
    request.Method = "POST";
    request.ContentType = "text/plain";
    Stream serverStream = request.GetRequestStream();
    serverStream.Write(fileStream, 0, fileStream.Length);
    serverStream.Close();
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        int statusCode = (int)response.StatusCode;
        StreamReader reader = new StreamReader(response.GetResponseStream());
    }
}

我已关闭防火墙和Internet连接,但该错误仍然存​​在。有没有更好的测试上传方法的方法?

堆栈跟踪:

在System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket
s4,Socket s6,Socket&socket,IPAddress&地址,ConnectSocketState状态,IAsyncResult
asyncResult,Int32超时,例外和例外)


阅读 1294

收藏
2020-05-19

共1个答案

一尘不染

“主动拒绝”表示您尝试连接时主机发送了重置而不是确认。因此,这不是您的代码中的问题。有防火墙阻止了连接,或者承载服务的进程没有在该端口上侦听。这可能是因为它根本没有运行,或者是因为它在其他端口上监听。

一旦开始托管服务的过程,请尝试netstat -anb(需要管理员特权)以验证其是否正在运行并正在侦听预期的端口。

更新:在Linux上,您可能需要这样做netstat -anp

2020-05-19