Java TCPEchoClient
ในบทความตอนที่แล้วเกี่ยวกับ TCPEchoServer ซึ่งจะแสดงข้อความตอบกลับมาเมื่อเราเข้าใช้บริการผ่านทาง telnet ในตอนนี้ก็จะเป็นการเขียนโปรแกรมฝั่ง client ที่จะทำหน้าที่คุยกับโปรแกรมฝั่ง server ของตอนที่แล้ว ซึ่งขั้นตอนของฝ่าย client ก็ไม่มีอะไรมาก ขั้นแรกก็ทำการสร้าง socket ไปยัง server และ port ของ server โดยที่นี้มีการประกาศตัวแปร
private static InetAddress host;
ซึ่งเป็นตัวแปรแบบ InetAddress หลังจากนั้นทำการกำหนด IP ของเครื่องตัวเองซึ่งใช้คำสั่งนี้ครับ
host = InetAddress.getLocalHost();
หลังจากนั้นก็มีการสร้าง method เพื่อประมวลผลการทำงานกับ server ซึ่งมีชื่อว่า accessServer() ที่จะทำหน้าที่กำหนด inputStream และ OutputStream คล้ายๆกับโปรแกรมที่ผ่านมาแล้วทำการส่งข้อความไปมาระหว่าง server
ตัวอย่างโค้ดครับ
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoClient
{
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("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer()
{
Socket link = null; //Step 1.
try
{
link = new Socket(host,PORT); //Step 1.
Scanner input =new Scanner(link.getInputStream()); //Step 2.
PrintWriter output =new PrintWriter(link.getOutputStream(),true); //Step 2.
//Set up stream for keyboard entry...
Scanner userEntry = new Scanner(System.in);
String message, response;
do
{
System.out.print("Enter message: ");
message = userEntry.nextLine();
output.println(message); //Step 3.
response = input.nextLine(); //Step 3.
System.out.println("\nSERVER> "+response);
}while (!message.equals("***CLOSE***"));
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close(); //Step 4.
}
catch(IOException ioEx)
{
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
Tags: JAVA, java.net, network programming, จาวา, ภาษาจาวา
Comments:1