Using Sockets in Java - Client

本文介绍如何使用Java创建TCP客户端程序,包括建立连接、设置输入输出流、发送接收数据及关闭连接等步骤。示例代码展示了具体实现过程。

Introduction

In this article I will demonstrate how to create a client program using Java, this article is the continuation of the previous article that I have write about creating a server program.To understand this article I recommand that you have already read the first one :(JavaSockets.aspx)

Using the code

The code is almost similar with the server code, to create a client you need to follow only four steps :

1.Establish a connection to server

2.Set up input and output streams

3.Send and receive data

4.Close the connection

Let's take the first step :

1.We have to create a Socket object, supplying its constructor with the following arguments:

  • the server's IP address (this is InetAddress)
  • the appropiate port number for the service

The port number for server and client programs must be the same, of course !

To be more easy we will place the client and the server on the same host, which will alow us to retrieve the IP address by calling static methid getLocalHost of class InetAddress.

         Socket link = new Socket(InetAddress.getLocalHost(), 1234);          

2.These are set up in exactly the same way as the server streams were set up (by calling methods getInputStream and getOutputStream of the Socket object that was created in step 2 in the previous article (JavaSockets.aspx).

3.The Scanner object at the client end will receive messages sent by the PrintWriter object at the server end, while the PrintWriter object at the client end will send messages that are received by the Scanner object at the server end(using method nextLine and println).

4.This is exactly the same as for the server process :

    link.close();

 

Entire code

Collapse
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);
            }
        }
    }
}
 
For more information or for any kind of clarification please don't hesitate to contact me : mihailescu.marius@yahoo.com, until then I wish you all a HAPPY CODING

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值