ในบทความนี้ก็เป็นเรื่อง java network programming ที่ต่อจากบทความก่อน ซึ่งเป็น server แบบ Multithread ให้บริการกับเครื่อง Client ได้หลายเครื่องพร้อมกัน ในส่วนของโค้ดฝ่าย client นั้นก็จะไม่ค่อยมีอะไรมากคล้ายกับ client ที่รันกับ server ที่ไม่ทำงานแบบ Multithread ซึ่งต่อไปก็ไปดู ตัวอย่างภาษาจาวาและผลการลัพธ์กันเลยดีกว่า
[sourcecode language=”java”]
import java.io.*;
import java.net.*;
import java.util.*;
public class MultiEchoClient
{
private static InetAddress host;
private static final int PORT = 1234;
public static void main(String[] args)
{
try
{
host = InetAddress.getLocalHost();
}
catch (UnknownHostException uhEx)
{
System.out.println(“\nHost ID not found!\n”);
System.exit(1);
}
sendMessage();
}
private static void sendMessage()
{
Socket socket = null;
try
{
socket = new Socket(host,PORT);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(),true);
//Set up stream for keyboard entry…
Scanner userEntry = new Scanner(System.in);
String message, response;
do
{
System.out.println(“Enter message (‘QUIT’ to exit): “);
message = userEntry.nextLine();
//Send message to server on the
//Socket ‘ s output stream
//Accept response from server on the
//socket’s input stream…
networkOutput.println(message);
response = networkInput.nextLine();
//Display server’s response to user…
System.out.println(“\nSERVER”+ response);
}
while (!message.equals(“QUIT”));
}
catch (IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
System.out.println(“\nClosing connection..”);
socket.close();
}
catch (IOException ioEx)
{
System.out.println(“Unable to disconnect!”);
System.exit(1);
}
}
}
}
[/sourcecode]
ซึ่งจะเห็นว่า โค้ดทาง client ยังเหมือนเดิมกับ server ที่ให้บริการเครื่องเดียวต่างกันก็โค้ด server ที่สามารถให้บริการได้หลายเครื่อง ถ้าใครสงสัยเรื่องโค้ด client ให้กลับไปดูบทความก่อนๆๆนะครับ
บทความที่เกี่ยวข้อง