我寫這個F#回聲服務器:這個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())
這個程序可以這樣做:
- 呼應客戶端的消息
- 時所說的 '左' 的客戶,回報 '正確'
- 當客戶說'退出'時,關閉連接
但是當我運行編程時,當客戶端發送 '左',獲得 '右',並派 '退出',我得到這個異常:
not handled exception: System.ObjectDisposedException: (con't write to closed) TextWriter。 in [email protected]e(Exception e) in [email protected](Trampoline this, FSharpFunc
2 action) in Microsoft.FSharp.Control.Trampoline.ExecuteAction(FSharpFunc
2 firstAction) in Microsoft.FSharp.Control.TrampolineHolder.Protect(FSharpFunc`2 firstAction) in [email protected](Object state) in System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, BooleanpreserveSyncCtx) in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) in System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() in System.Threading.ThreadPoolWorkQueue.Dispatch() in System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() . . .(press any key to continue)
Screenshot of program in action
Screenshot of exception
如何解決這個問題?
你會得到什麼例外?你能否將這些信息添加到你的問題中。 – s952163
請將問題複製並粘貼到問題中,而不是使用屏幕截圖。例外情況的屏幕截圖不允許任何人Google搜索例外文本,所以它的幫助不大。另外,請讓我們看看異常的整個堆棧跟蹤,而不是僅僅看第一行。看到堆棧跟蹤的其餘部分可能會提供一些線索,讓別人找出導致異常的原因。 – rmunn