F# -- TCP/IP小测试
下面是服务器端代码:
// Learn more about F# at http://fsharp.net // See the 'F# Tutorial' project for more help. open System.Net.Sockets open System.Net open System.IO open System open System.Collections.Generic type System.Net.Sockets.TcpListener with member this.AsyncAcceptTcpClient() = Async.FromBeginEnd(this.BeginAcceptTcpClient,this.EndAcceptTcpClient) type Server() = class member this.Start() = let tcpListener = new TcpListener(System.Net.IPAddress.Loopback, 4242) tcpListener.Start() while(true) do if(tcpListener.Pending()) then let proc = async{ try let! client = tcpListener.AsyncAcceptTcpClient() let strPipe = client.GetStream() let strReader = new StreamReader(strPipe) let strWriter = new StreamWriter(strPipe) while(true) do let buffer = Array.create 216 0uy let read = strPipe.Read(buffer,0,216) let allText = System.Text.Encoding.UTF8.GetString(buffer,0,read) printfn "Recieve from client: %s" (allText) strWriter.Write("Got From Server:") allText |> strWriter.WriteLine strWriter.Flush() with _ -> printfn "丢失连接,重新连接吧" } proc |> Async.Start end [<EntryPoint>] let main argv = (new Server()).Start() 0 // return an integer exit code
客户端代码:
// Learn more about F# at http://fsharp.net // See the 'F# Tutorial' project for more help. open System.Windows.Forms open System open System.Drawing open System.Net.Sockets open System.IO let form = new Form() form.Text <- "Test" let input = new System.Windows.Forms.TextBox() input.Multiline <- true input.Dock <- DockStyle.Top input.Height <- form.Height / 10 * 2 form.Controls.Add(input) let output = new System.Windows.Forms.TextBox() output.Multiline <- true output.ReadOnly <- true output.Dock <- DockStyle.Bottom output.Height <- form.Height / 10 * 6 output.ScrollBars <- ScrollBars.Both output.ScrollToCaret() let client = new TcpClient() client.Connect("172.0.0.1",4242) let sr = new StreamReader(client.GetStream()) let sw = new StreamWriter(client.GetStream()) form.Controls.Add(output) //发送消息 let keyUp() = //多于 一行 ,回车 if(input.Lines.Length > 1) then let text = input.Text if (text <> null && text <> "") then try sw.WriteLine(text) sw.Flush() with err -> printfn "Server error" input.Text <- "" input.KeyUp.Add(fun _ -> keyUp()) let getBackStr() = let getStr() = while(true) do let text = sr.ReadLine() if(text<>"" && text<>null)then printfn "%s"text output.Text <- output.Text + text output.AppendText(System.Environment.NewLine) //另起一个专门负责接受服务器回复的Thread let thread = new Threading.Thread(new Threading.ThreadStart(fun _ -> getStr())) thread.Start() form.Load.Add(fun _ -> getBackStr()) form.SizeChanged.Add(fun _ -> input.Height <- form.Height / 10 * 2 output.Height <- form.Height / 10 * 6 ) form.Closing.Add(fun _ -> Application.Exit()) [<EntryPoint>] let main argv = do Application.Run(form) 0 // return an integer exit code
更新一下, 支持异步运行。 多个Form同时运行。 下个版本实现多个之间交流。。