溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java Socket編程是什么

發(fā)布時間:2021-11-25 09:17:17 來源:億速云 閱讀:177 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“Java Socket編程是什么”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Java Socket編程是什么”這篇文章吧。

1.什么是socket

所謂socket通常也稱作"套接字",用于描述IP地址和端口,是一個通信鏈的句柄。應(yīng)用程序通常通過"套接字"向網(wǎng)絡(luò)發(fā)出請求或者應(yīng)答網(wǎng)絡(luò)請求。

以J2SDK-1.3為例,Socket和ServerSocket類庫位于java.net包中。ServerSocket用于服務(wù)器端,Socket是建立網(wǎng)絡(luò)連接時使用的。在連接成功時,應(yīng)用程序兩端都會產(chǎn)生一個Socket實例,操作這個實例,完成所需的會話。對于一個網(wǎng)絡(luò)連接來說,套接字是平等的,并沒有差別,不因為在服務(wù)器端或在客戶端而產(chǎn)生不同級別。不管是Socket還是ServerSocket它們的工作都是通過SocketImpl類及其子類完成的。

重要的Socket API:

java.net.Socket繼承于java.lang.Object,有八個構(gòu)造器,其方法并不多,下面介紹使用最頻繁的三個方法,其它方法大家可以見JDK-1.3文檔。

.Accept方法用于產(chǎn)生"阻塞",直到接受到一個連接,并且返回一個客戶端的Socket對象實例。"阻塞"是一個術(shù)語,它使程序運行暫時"停留"在這個地方,直到一個會話產(chǎn)生,然后程序繼續(xù);通常"阻塞"是由循環(huán)產(chǎn)生的。

.getInputStream方法獲得網(wǎng)絡(luò)連接輸入,同時返回一個IutputStream對象實例,。

.getOutputStream方法連接的另一端將得到輸入,同時返回一個OutputStream對象實例。

注意:其中g(shù)etInputStream和getOutputStream方法均會產(chǎn)生一個IOException,它必須被捕獲,因為它們返回的流對象,通常都會被另一個流對象使用。

2.如何開發(fā)一個Server-Client模型的程序

開發(fā)原理:

服務(wù)器,使用ServerSocket監(jiān)聽指定的端口,端口可以隨意指定(由于1024以下的端口通常屬于保留端口,在一些操作系統(tǒng)中不可以隨意使用,所以建議使用大于1024的端口),等待客戶連接請求,客戶連接后,會話產(chǎn)生;在完成會話后,關(guān)閉連接。

客戶端,使用Socket對網(wǎng)絡(luò)上某一個服務(wù)器的某一個端口發(fā)出連接請求,一旦連接成功,打開會話;會話完成后,關(guān)閉Socket??蛻舳瞬恍枰付ù蜷_的端口,通常臨時的、動態(tài)的分配一個1024以上的端口。

{建立服務(wù)器}

import java.net.*;
import java.io.*;
public class Server
{
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server()
{
try
{
ss = new ServerSocket(10000);
while (true)
{
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
String line = in.readLine();
out.println("you input is :" + line);
out.close();
in.close();
socket.close();
}
ss.close();
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Server();
}
}

這個程序建立了一個服務(wù)器,它一直監(jiān)聽10000端口,等待用戶連接。在建立連接后給客戶端返回一段信息,然后結(jié)束會話。這個程序一次只能接受一個客戶連接。

{建立客戶端}

import java.io.*;
import java.net.*;
public class Client
{
Socket socket;
BufferedReader in;
PrintWriter out;
public Client()
{
try
{
socket = new Socket("xxx.xxx.xxx.xxx", 10000);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
out.println(line.readLine());
line.close();
out.close();
in.close();
socket.close();
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Client();
}
}

這個客戶端連接到地址為xxx.xxx.xxx.xxx的服務(wù)器,端口為10000,并從鍵盤輸入一行信息,發(fā)送到服務(wù)器,然后接受服務(wù)器的返回信息,***結(jié)束會話。

第二步 多個客戶同時連接

在實際的網(wǎng)絡(luò)環(huán)境里,同一時間只對一個用戶服務(wù)是不可行的。一個優(yōu)秀的網(wǎng)絡(luò)服務(wù)程序除了能處理用戶的輸入信息,還必須能夠同時響應(yīng)多個客戶端的連接請求。在java中,實現(xiàn)以上功能特點是非常容易的。

設(shè)計原理:

主程序監(jiān)聽一端口,等待客戶接入;同時構(gòu)造一個線程類,準(zhǔn)備接管會話。當(dāng)一個Socket會話產(chǎn)生后,將這個會話交給線程處理,然后主程序繼續(xù)監(jiān)聽。運用Thread類或Runnable接口來實現(xiàn)是不錯的辦法。

{實現(xiàn)消息共享}

import java.io.*;
import java.net.*;
public class Server extends ServerSocket
{
private static final int SERVER_PORT = 10000;
public Server() throws IOException
{
super(SERVER_PORT);
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket);
}
}
catch (IOException e)
{}
finally
{
close();
}
}
//--- CreateServerThread
class CreateServerThread extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
public CreateServerThread(Socket s) throws IOException
{
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312"));
out = new PrintWriter(client.getOutputStream(), true);
out.println("--- Welcome ---");
start();
}
public void run()
{
try
{
String line = in.readLine();
while (!line.equals("bye"))
{
String msg = createMessage(line);
out.println(msg);
line = in.readLine();
}
out.println("--- See you, bye! ---");
client.close();
}
catch (IOException e)
{}
}
private String createMessage(String line)
{
xxxxxxxxx;
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
}

這個程序監(jiān)聽10000端口,并將接入交給CreateServerThread線程運行。CreateServerThread線程接受輸入,并將輸入回應(yīng)客戶,直到客戶輸入"bye",線程結(jié)束。我們可以在createMessage方法中,對輸入進(jìn)行處理,并產(chǎn)生結(jié)果,然后把結(jié)果返回給客戶。

第三步 實現(xiàn)信息共享:在Socket上的實時交流

網(wǎng)絡(luò)的偉大之一也是信息共享,Server可以主動向所有Client廣播消息,同時Client也可以向其它Client發(fā)布消息。下面看看如何開發(fā)一個可以實時傳遞消息的程序。

設(shè)計原理:

服務(wù)器端接受客戶端的連接請求,同時啟動一個線程處理這個連接,線程不停的讀取客戶端輸入,然后把輸入加入隊列中,等候處理。在線程啟動的同時將線程加入隊列中,以便在需要的時候定位和取出。

{源碼}

import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
public class Server extends ServerSocket
{
private static ArrayList User_List = new ArrayList();
private static ArrayList Threader = new ArrayList();
private static LinkedList Message_Array = new LinkedList();
private static int Thread_Counter = 0;
private static boolean isClear = true;
protected static final int SERVER_PORT = 10000;
protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true);
public Server() throws FileNotFoundException, IOException
{
super(SERVER_PORT);
new Broadcast();
//append connection log
Calendar now = Calendar.getInstance();
String str = "[" + now.getTime().toString() + "] Accepted a connection1512";
byte[] tmp = str.getBytes();
LOG_FILE.write(tmp);
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket);
}
}
finally
{
close();
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
//--- Broadcast
class Broadcast extends Thread
{
public Broadcast()
{
start();
}
public void run()
{
while (true)
{
if (!isClear)
{
String tmp = (String)Message_Array.getFirst();
for (int i = 0; i < Threader.size(); i++)
{
CreateServerThread client = (CreateServerThread)Threader.get(i);
client.sendMessage(tmp);
}
Message_Array.removeFirst();
isClear = Message_Array.size() > 0 ? false : true;
}
}
}
}
//--- CreateServerThread
class CreateServerThread extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
private String Username;
public CreateServerThread(Socket s) throws IOException
{
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
out.println("--- Welcome to this chatroom ---");
out.println("Input your nickname:");
start();
}
public void sendMessage(String msg)
{
out.println(msg);
}
public void run()
{
try
{
int flag = 0;
Thread_Counter++;
String line = in.readLine();
while (!line.equals("bye"))
{
if (line.equals("l"))
{
out.println(listOnlineUsers());
line = in.readLine();
continue;
}
if (flag++ == 0)
{
Username = line;
User_List.add(Username);
out.println(listOnlineUsers());
Threader.add(this);
pushMessage("[< " + Username + " come on in >]");
}
else
{
pushMessage("<" + Username + ">" + line);
}
line = in.readLine();
}
out.println("--- See you, bye! ---");
client.close();
}
catch (IOException e)
{}
finally
{
try
{
client.close();
}
catch (IOException e)
{}
Thread_Counter--;
Threader.remove(this);
User_List.remove(Username);
pushMessage("[< " + Username + " left>]");
}
}
private String listOnlineUsers()
{
String s ="-+- Online list -+-1512";
for (int i = 0; i < User_List.size(); i++)
{
s += "[" + User_List.get(i) + "]1512";
}
s += "-+---------------------+-";
return s;
}
private void pushMessage(String msg)
{
Message_Array.addLast(msg);
isClear = false;
}
}
}

Java Socket編程是什么

這就是程序運行后,多用戶登陸并且輸入信息后的屏幕。實現(xiàn)了信息的實時廣播。用戶輸入"l"就可以列出在線人員表。

以上是“Java Socket編程是什么”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI