【发布时间】:2016-12-06 01:05:41
【问题描述】:
我已经编写了这个 f# echo 服务器:
open System.Net
open System.Net.Sockets
open System.IO
open System
open System.Text
open System.Collections.Generic
let addr = IPAddress.Parse("127.0.0.1")
let listener = new TcpListener(addr, 2000)
listener.Start()
let rec loop2(c:TcpClient,sr:StreamReader,sw:StreamWriter)=async {
let line=sr.ReadLine()
if not(line=null) then
match line with
|"quit"->
sr.Close()
sw.Close()
c.Close()
|_ ->
if line.Equals("left") then
sw.WriteLine("right")
return! loop2(c,sr,sw)
sw.WriteLine(line)
return! loop2(c,sr,sw)
else
sr.Close()
sw.Close()
c.Close()
}
let loop()=async {
while true do
let c=listener.AcceptTcpClient()
let d = c.GetStream()
let sr = new StreamReader(d)
let sw = new StreamWriter(d)
sw.AutoFlush<-true
Async.Start(loop2(c,sr,sw))
}
Async.RunSynchronously(loop())
这个程序可以做到:
- 回显客户的消息
- 当客户说“左”时,返回“右”
- 当客户端说“退出”时,关闭连接
但是当我运行程序时,当客户端发送“左”、“右”和“退出”时,我得到了这个异常:
未处理的异常:System.ObjectDisposedException:(不写 关闭)TextWriter。在 Microsoft.FSharp.Control.CancellationTokenOps.Start@1192-1.Invoke(异常 e)在.$Control.loop@419-40(蹦床这个, FSharpFunc
2 action) in Microsoft.FSharp.Control.Trampoline.ExecuteAction(FSharpFunc2 第一个动作)在 Microsoft.FSharp.Control.TrampolineHolder.Protect(FSharpFunc`2 第一个动作)在 .$Control.-ctor@476-1.Invoke(Object state) in System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(对象 状态)在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext、ContextCallback 回调、对象状态、 BooleanpreserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext、ContextCallback 回调、对象状态、布尔值 preserveSyncCtx) 在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 在 System.Threading.ThreadPoolWorkQueue.Dispatch() 中 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() 。 . .(按任意键继续)
Screenshot of program in action
Screenshot of exception
我该如何解决这个问题?
【问题讨论】:
-
你得到什么异常?您可以将该信息添加到您的问题中吗?
-
请将异常复制并粘贴到问题中,而不是使用屏幕截图。异常的屏幕截图不允许任何人通过 Google 搜索异常文本,因此它的帮助较小。另外,请让我们查看异常的整个堆栈跟踪,而不仅仅是第一行。查看堆栈跟踪的其余部分可能会提供一些线索,让人们找出导致异常的原因。
标签: f#