Panduan untuk Soket Java

1. Gambaran keseluruhan

Istilah pengaturcaraan soket merujuk kepada program penulisan yang dijalankan di beberapa komputer di mana semua perangkat terhubung satu sama lain menggunakan rangkaian.

Terdapat dua protokol komunikasi yang dapat digunakan seseorang untuk pengaturcaraan soket: User Datagram Protocol (UDP) dan Transfer Control Protocol (TCP) .

Perbezaan utama antara keduanya adalah bahawa UDP tidak bersambung, yang bermaksud tidak ada sesi antara klien dan pelayan sementara TCP berorientasikan sambungan, yang bermaksud sambungan eksklusif mesti dibuat terlebih dahulu antara klien dan pelayan agar komunikasi berlaku.

Tutorial ini memberikan pengenalan kepada pengaturcaraan soket melalui rangkaian TCP / IP dan menunjukkan cara menulis aplikasi klien / pelayan di Java. UDP bukan protokol arus perdana dan dengan demikian mungkin tidak sering dijumpai.

2. Penyediaan Projek

Java menyediakan koleksi kelas dan antara muka yang mengurus perincian komunikasi tahap rendah antara klien dan pelayan.

Ini kebanyakan terdapat dalam pakej java.net , jadi kita perlu membuat import berikut:

import java.net.*;

Kami juga memerlukan pakej java.io yang memberi kami aliran input dan output untuk menulis dan membaca dari semasa berkomunikasi:

import java.io.*;

Demi kesederhanaan, kami akan menjalankan program pelanggan dan pelayan kami di komputer yang sama. Sekiranya kita melaksanakannya di komputer rangkaian yang berbeza, satu-satunya perkara yang akan berubah adalah alamat IP, dalam hal ini, kita akan menggunakan localhost pada 127.0.0.1 .

3. Contoh Ringkas

Mari tangan kita kotor dengan contoh paling asas yang melibatkan pelanggan dan pelayan . Ini akan menjadi aplikasi komunikasi dua hala di mana pelanggan menyapa pelayan dan pelayan bertindak balas.

Mari buat aplikasi pelayan di kelas bernama GreetServer.java dengan kod berikut.

Kami memasukkan kaedah utama dan pemboleh ubah global untuk menarik perhatian bagaimana kami menjalankan semua pelayan dalam artikel ini. Dalam contoh yang lain dalam artikel, kami akan menghilangkan kod yang lebih berulang seperti ini:

public class GreetServer { private ServerSocket serverSocket; private Socket clientSocket; private PrintWriter out; private BufferedReader in; public void start(int port) { serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String greeting = in.readLine(); if ("hello server".equals(greeting)) { out.println("hello client"); } else { out.println("unrecognised greeting"); } } public void stop() { in.close(); out.close(); clientSocket.close(); serverSocket.close(); } public static void main(String[] args) { GreetServer server=new GreetServer(); server.start(6666); } }

Mari juga buat pelanggan bernama GreetClient.java dengan kod ini:

public class GreetClient { private Socket clientSocket; private PrintWriter out; private BufferedReader in; public void startConnection(String ip, int port) { clientSocket = new Socket(ip, port); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } public String sendMessage(String msg) { out.println(msg); String resp = in.readLine(); return resp; } public void stopConnection() { in.close(); out.close(); clientSocket.close(); } }

Mari mulakan pelayan; di IDE anda, anda melakukannya dengan hanya menjalankannya sebagai aplikasi Java.

Dan sekarang mari kita mengirim ucapan ke pelayan menggunakan ujian unit, yang mengesahkan bahawa pelayan sebenarnya mengirim ucapan sebagai tindak balas:

@Test public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() { GreetClient client = new GreetClient(); client.startConnection("127.0.0.1", 6666); String response = client.sendMessage("hello server"); assertEquals("hello client", response); }

Jangan bimbang jika anda tidak sepenuhnya memahami apa yang berlaku di sini, kerana contoh ini bertujuan untuk memberi kita gambaran tentang apa yang diharapkan di kemudian hari.

Pada bahagian berikut, kami akan membedah komunikasi soket menggunakan contoh mudah ini dan menyelami lebih terperinci dengan lebih banyak contoh.

4. Bagaimana Soket Berfungsi

Kami akan menggunakan contoh di atas untuk melangkah ke bahagian yang berbeza dari bahagian ini.

Secara definisi, soket adalah satu titik akhir hubungan komunikasi dua hala antara dua program yang berjalan pada komputer yang berlainan di rangkaian. Soket terikat pada nombor port sehingga lapisan transport dapat mengenal pasti aplikasi yang akan dikirimkan oleh data.

4.1. Pelayan

Biasanya, pelayan berjalan pada komputer tertentu di rangkaian dan mempunyai soket yang terikat dengan nombor port tertentu. Dalam kes kami, kami menggunakan komputer yang sama dengan pelanggan dan memulakan pelayan di port 6666 :

ServerSocket serverSocket = new ServerSocket(6666);

The server just waits, listening to the socket for a client to make a connection request. This happens in the next step:

Socket clientSocket = serverSocket.accept();

When the server code encounters the accept method, it blocks until a client makes a connection request to it.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket, clientSocket, bound to the same local port, 6666, and also has its remote endpoint set to the address and port of the client.

At this point, the new Socket object puts the server in direct connection with the client, we can then access the output and input streams to write and receive messages to and from the client respectively:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

From here onwards, the server is capable of exchanging messages with the client endlessly until the socket is closed with its streams.

However, in our example the server can only send a greeting response before it closes the connection, this means that if we ran our test again, the connection would be refused.

To allow continuity in communication, we will have to read from the input stream inside a while loop and only exit when the client sends a termination request, we will see this in action in the following section.

For every new client, the server needs a new socket returned by the accept call. The serverSocket is used to continue to listen for connection requests while tending to the needs of the connected clients. We have not allowed for this yet in our first example.

4.2. The Client

The client must know the hostname or IP of the machine on which the server is running and the port number on which the server is listening.

To make a connection request, the client tries to rendezvous with the server on the server's machine and port:

Socket clientSocket = new Socket("127.0.0.1", 6666);

The client also needs to identify itself to the server so it binds to a local port number, assigned by the system, that it will use during this connection. We don't deal with this ourselves.

The above constructor only creates a new socket when the server has accepted the connection, otherwise, we will get a connection refused exception. When successfully created we can then obtain input and output streams from it to communicate with the server:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

The input stream of the client is connected to the output stream of the server, just like the input stream of the server is connected to the output stream of the client.

5. Continuous Communication

Our current server blocks until a client connects to it and then blocks again to listen to a message from the client, after the single message, it closes the connection because we have not dealt with continuity.

So it is only helpful in ping requests, but imagine we would like to implement a chat server, continuous back and forth communication between server and client would definitely be required.

We will have to create a while loop to continuously observe the input stream of the server for incoming messages.

Let's create a new server called EchoServer.java whose sole purpose is to echo back whatever messages it receives from clients:

public class EchoServer { public void start(int port) { serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (".".equals(inputLine)) { out.println("good bye"); break; } out.println(inputLine); } }

Notice that we have added a termination condition where the while loop exits when we receive a period character.

We will start EchoServer using the main method just as we did for the GreetServer. This time, we start it on another port such as 4444 to avoid confusion.

The EchoClient is similar to GreetClient, so we can duplicate the code. We are separating them for clarity.

In a different test class, we shall create a test to show that multiple requests to the EchoServer will be served without the server closing the socket. This is true as long as we are sending requests from the same client.

Dealing with multiple clients is a different case, which we shall see in a subsequent section.

Let's create a setup method to initiate a connection with the server:

@Before public void setup() { client = new EchoClient(); client.startConnection("127.0.0.1", 4444); }

We will equally create a tearDown method to release all our resources, this is best practice for every case where we use network resources:

@After public void tearDown() { client.stopConnection(); }

Let's then test our echo server with a few requests:

@Test public void givenClient_whenServerEchosMessage_thenCorrect() { String resp1 = client.sendMessage("hello"); String resp2 = client.sendMessage("world"); String resp3 = client.sendMessage("!"); String resp4 = client.sendMessage("."); assertEquals("hello", resp1); assertEquals("world", resp2); assertEquals("!", resp3); assertEquals("good bye", resp4); }

This is an improvement over the initial example, where we would only communicate once before the server closed our connection; now we send a termination signal to tell the server when we're done with the session.

6. Server With Multiple Clients

Much as the previous example was an improvement over the first one, it is still not that great a solution. A server must have the capacity to service many clients and many requests simultaneously.

Handling multiple clients is what we are going to cover in this section.

Another feature we will see here is that the same client could disconnect and reconnect again, without getting a connection refused exception or a connection reset on the server. Previously we were not able to do this.

This means that our server is going to be more robust and resilient across multiple requests from multiple clients.

How we will do this is to create a new socket for every new client and service that client's requests on a different thread. The number of clients being served simultaneously will equal the number of threads running.

The main thread will be running a while loop as it listens for new connections.

Enough talk, let's create another server called EchoMultiServer.java. Inside it, we will create a handler thread class to manage each client's communications on its socket:

public class EchoMultiServer { private ServerSocket serverSocket; public void start(int port) { serverSocket = new ServerSocket(port); while (true) new EchoClientHandler(serverSocket.accept()).start(); } public void stop() { serverSocket.close(); } private static class EchoClientHandler extends Thread { private Socket clientSocket; private PrintWriter out; private BufferedReader in; public EchoClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (".".equals(inputLine)) { out.println("bye"); break; } out.println(inputLine); } in.close(); out.close(); clientSocket.close(); } }

Notice that we now call accept inside a while loop. Every time the while loop is executed, it blocks on the accept call until a new client connects, then the handler thread, EchoClientHandler, is created for this client.

What happens inside the thread is what we previously did in the EchoServer where we handled only a single client. So the EchoMultiServer delegates this work to EchoClientHandler so that it can keep listening for more clients in the while loop.

Kami masih akan menggunakan EchoClient untuk menguji pelayan, kali ini kami akan membuat beberapa pelanggan yang masing-masing menghantar dan menerima banyak mesej dari pelayan.

Mari mulakan pelayan kami menggunakan kaedah utamanya di port 5555 .

Untuk kejelasan, kami masih akan meletakkan ujian di suite baru:

@Test public void givenClient1_whenServerResponds_thenCorrect() { EchoClient client1 = new EchoClient(); client1.startConnection("127.0.0.1", 5555); String msg1 = client1.sendMessage("hello"); String msg2 = client1.sendMessage("world"); String terminate = client1.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); } @Test public void givenClient2_whenServerResponds_thenCorrect() { EchoClient client2 = new EchoClient(); client2.startConnection("127.0.0.1", 5555); String msg1 = client2.sendMessage("hello"); String msg2 = client2.sendMessage("world"); String terminate = client2.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); }

Kami dapat membuat sebilangan besar kes ujian ini sesuka hati, masing-masing melahirkan klien baru dan pelayan akan melayani semuanya.

7. Kesimpulannya

Dalam tutorial ini, kami memfokuskan pada pengenalan pada pengaturcaraan soket melalui TCP / IP dan menulis aplikasi Pelanggan / Pelayan sederhana di Java.

Kod sumber lengkap untuk artikel boleh didapati - seperti biasa - dalam projek GitHub.