tailieunhanh - lập trình android (phần 5)
Tham khảo tài liệu 'lập trình android (phần 5)', 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ả | 176 Chapter 6 Networking and web services try socket new Socket ip port --1 Create client writer new BufferedWriter Dj Socket new OutputStreamWriter E Establish BufferedWriter for input reader new BufferedReader new InputStreamReader F Establish BufferedReaderfor output String input socketData input n 0 1 --1 Write to G socket output --1 Get socket output Hp output send EXIT and close EXIT n 0 5 . . . catches and reader writer and socket closes omitted for brevity . . . onCreate omitted for brevity return output Here we use the onCreate method to call a private helper callSocket method O and set the output to a Textview . Within the callSocket method we create a Socket to represent the client side of our connection D and we establish a writer for the input E and a reader for the output F. With the housekeeping taken care of we then write to the socket G which communicates with the server and get the output value to return . A socket is probably the lowest-level networking usage in Android you will encounter. Using a raw socket while abstracted a great deal still leaves many of the details up to you especially server-side details threading and queuing . Although you may run up against situations in which either you have to use a raw socket the server side is already built or you elect to use one for one reason or another higher-level solutions such as leveraging HTTP normally have decided advantages. Working with HTTP As we discussed in the previous section you can use a raw socket to transfer IP data to and from a server with Android. This is an important approach to be aware of so that you know you have that option and so that you understand a bit about the underlying details. Nevertheless you may want to avoid this technique where possible and instead take advantage of existing server products
đang nạp các trang xem trước