Đang chuẩn bị liên kết để tải về tài liệu:
Foundations of F#.Net phần 9
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'foundations of f#.net phần 9', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 246 CHAPTER 10 DISTRIBUTED APPLICATIONS open System.Net.Sockets open System.Threading open System.Windows.Forms let form let temp new Form temp.Text - F Talk Client temp.Closing.Add fun e - Application.Exit Environment.Exit 0 let output new TextBox Dock DockStyle.Fill ReadOnly true Multiline true temp.Controls.Add output let input new TextBox Dock DockStyle.Bottom Multiline true temp.Controls.Add input let tc new TcpClient tc.Connect localhost 4242 let load let run let sr new StreamReader tc.GetStream while true do let text sr.ReadLine if text null text then temp.Invoke new MethodInvoker fun - output.AppendText text Environment.NewLine output.SelectionStart - output.Text.Length ignore let t new Thread new ThreadStart run t.Start temp.Load.Add fun _ - load let sw new StreamWriter tc.GetStream let keyUp _ if input.Lines.Length 1 then let text input.Text if text null text then CHAPTER 10 DISTRIBUTED APPLICATIONS 247 begin try sw.WriteLine text sw.Flush with err - MessageBox.Show sprintf Server error n n O err ignore end input.Text - input.KeyUp.Add fun _ - keyUp e temp STAThread do Application.Run form Figure 10-1 shows the resulting client-server application. Figure 10-1. The chat client-server application Now you ll look at how the client in Listing 10-2 works. The first portion of code in the client is taken up initializing various aspects of the form this is not of interest to you at the moment though you can find details of how WinForms applications work in Chapter 8. The first part of Listing 10-2 that is relevant to TCP IP sockets programming is when you connect to the server. You do this by creating a new instance of the TcpClient class and calling its Connect method 248 CHAPTER 10 DISTRIBUTED APPLICATIONS let tc new TcpClient tc.Connect localhost 4242 In this example you specify localhost which is the local computer and port 4242 which is the same port on which the server is listening. In a more realistic example you d probably give the DNS name of the server