1. 程式人生 > >Java網路程式設計之多執行緒Client-Server

Java網路程式設計之多執行緒Client-Server

前面廢話過了,現在就直接看程式碼吧!

ThreadedClient.java

package exercise01;
import java.io.*;
import java.net.*;

public class ThreadedClient {
    private String hostname;
    private int port;
    Socket socket = null;
    
    public ThreadedClient(String hostname, int port){
    	//constructor of the Client class
    	this.hostname = hostname;
    	this.port = port;
    }
    
    public void connect() throws UnknownHostException, IOException{
    	System.out.println("Attempting connect to "+ hostname +":"+port);
    	socket = new Socket(hostname,port);
    	System.out.println("Connection established!");
    }
    
    public void readResponse() throws IOException{
    	String userInput;
    	BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    	System.out.println("Response from the server:");
    	while((userInput = reader.readLine() )!= null ){
    		System.out.println(userInput);
    	}
    }
    
    public void askForTime() throws IOException{
    	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    	writer.write("Time?");
    	writer.newLine();
    	writer.flush();
    }
    
    public static void main(String[] argv){
    	//create an object for the current class Client
    	ThreadedClient client = new ThreadedClient("localhost",8181);
    	try{
    		//trying to establish a connection to the server
    		client.connect();
    		
    		//ask the server for time
    		client.askForTime();
    		
    		//if connection succeed, return the input contents
    		client.readResponse();
    		
    	}catch(UnknownHostException ukhe){
    		//if the host not found
    		System.err.println("Host unknown! Connection can not be established!");
    	}catch(IOException ioe){
    		//if the server doesn't work
    		System.err.println("Connection can not be established! The server may not be on! Check the error message! "+ioe.getMessage());
    	}
    }
    
    
}
ThreadedServer.java
package exercise01;
import java.io.*;
import java.net.*;
import java.util.Date;

public class ThreadedServer {
	private ServerSocket serverSocket;
	private int port;
	
	public ThreadedServer(int port){
		this.port = port;
	}
	
	//get the thread started
	public void start() throws IOException{
		System.out.println("Starting the server at the port: "+ port);
		serverSocket = new ServerSocket(port);
		
		//instantial an object client
		Socket client = null;
		
		//set the condition to be true for endless loops
		while(true){
			System.out.println("Waiting for clients...");
			client = serverSocket.accept();
			System.out.println("The following client has connected: " + client.getInetAddress().getCanonicalHostName());
			//A client has connected to the server
			Thread thread = new Thread(new SocketClientHandler(client));
			thread.start();
		}
	}
	
	/**
	 * instantial an object of class ThreadedServer and start the server
	 * 
	 * @param argv
	 */
	public static void main(String[] argv){
		//set the default port number
		int port = 8181;
		
		try{
			//initializing the socket server
			ThreadedServer threadedServer = new ThreadedServer(port);
			threadedServer.start();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
	}
}

class SocketClientHandler implements Runnable{

	private Socket client;
	
	public SocketClientHandler(Socket client){
		this.client = client;
	}
	
	/**
	 * get the thread started by the run method
	 */
	@Override
	public void run() {
		try{
			System.out.println("Thread started with name: " + Thread.currentThread().getName());
			readResponse();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}catch(InterruptedException ie){
			ie.printStackTrace();
		}
	}

	/**
	 * read the response from the server
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void readResponse() throws IOException, InterruptedException {
		String userInput;
		BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
		while(( userInput = reader.readLine())!= null){
			if(userInput.equals("Time?")){
				System.out.println("Request to send time! Sending time current.");
				sendTime();
				break;
			}
		}
	}

	/**
	 * send the current time to the server
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void sendTime() throws IOException, InterruptedException {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
		writer.write(new Date().toString());
		writer.flush();
		writer.close();
	}
	
}
是不是給你帶來了一點靈感呢?


相關推薦

Java網路程式設計執行Client-Server

前面廢話過了,現在就直接看程式碼吧! ThreadedClient.java package exercise01; import java.io.*; import java.net.*; public class ThreadedClient { privat

Java網路程式設計4.UDP網路程式設計執行優化

UDP網路程式設計之多執行緒優化——DatagramSocket類 1、UDP網路程式設計之多執行緒優化的思想 (1)一個執行緒實現客戶端——傳送資料 (2)一個執行緒實現伺服器端——接收資料

socket網路程式設計執行阻塞IO例項

先介紹一下網路層次結構、socket與TCP/UDP之間的關係。同步、非同步,阻塞、非阻塞的區別。 網路由下往上分為物理層、資料鏈路層、網路層、傳輸層、會話層、表示層和應用層。 IP 協議對應於網路層,TCP協議對應於傳輸層,HTTP協議對應於應用層,三者從本質上來說沒有可

Python網路程式設計執行

多執行緒 多執行緒舉例: import threading from time import sleep,ctime def sing(): for i in range(3): print("正在唱歌...%d"%i)

Java網路程式設計執行下載檔案設定顯示進度(一)

下載檔案的時候,如果為了使用者友好,都會給予進度條提醒使用者,那麼怎麼做呢? 其實很簡單,首先獲取伺服器檔案的大小urlConnection.getContentLength(),然後在讀取檔案過程計算檔案百分比增長即可 /** * 檔案下載工具 by sam on

Linux 下 C 網路程式設計 執行通訊 例項

簡單示例,有不對的地方,歡迎指點。 伺服器端 /* ============================================================================ Name : sockThreadServer

網路程式設計執行——GIL全域性直譯器鎖

網路程式設計之多執行緒——GIL全域性直譯器鎖 一、引子 定義: In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python b

java程式設計執行計算

/* *編寫兩個執行緒: *第一個執行緒計算2-1000000之間的質數及個數 *第二個執行緒計算1000000-2000000之間的質數 及個數 */ class myThread extends Thread{ private int a,b; //

併發程式設計執行執行安全

什麼是執行緒安全? 為什麼有執行緒安全問題? 當多個執行緒同時共享,同一個全域性變數或靜態變數,做寫的操作時,可能會發生資料衝突問題,也就是執行緒安全問題。但是做讀操作是不會發生資料衝突問題。 案例: 需求現在有100張火車票,有兩個視窗同時搶火車票,請使用多執行緒模擬搶票效果。 p

併發程式設計執行基礎

執行緒與程序區別 每個正在系統上執行的程式都是一個程序。每個程序包含一到多個執行緒。執行緒是一組指令的集合,或者是程式的特殊段,它可以在程式裡獨立執行。也可以把它理解為程式碼執行的上下文。所以執行緒基本上是輕量級的程序,它負責在單個程式裡執行多工。通常由作業系統負責多個執行緒的排程和執行。

java併發程式設計一一執行之間通訊(一)

1.多執行緒之間如何實現通訊 多執行緒之間通訊,其實就是多個執行緒在操作同一個資源,但是操作的動作不同。 1.1什麼是多執行緒之間通訊? 需求:第一個執行緒寫入(input)使用者,另一個執行緒讀取(out)使用者。實現讀一個,寫一個操作。 1.2多執行緒之間通訊需求?

java併發程式設計一一執行執行安全(四)

##1.java重排序 ###1.1資料依賴性 如果兩個操作訪問同一個變數時,且這兩個操作匯中有一個為寫操作,此時這兩個操作之間就 存在資料依賴性。資料依賴分下列三種類型。 名稱 程式碼示例 說明

java併發程式設計一一執行執行安全(三)

1.多執行緒的三大特性 1.1什麼是原子性 即一個操作或多個操作要麼全部執行並且執行的過程不會被任何因素打斷,要麼就都不執行。 一個很經典的例子就是銀行賬戶轉賬問題: 比如從賬戶A向賬戶B轉1000元,那麼必然包括2個操作:從賬戶A減去1000元,往賬戶B加上1000元。這2

java併發程式設計一一執行執行安全(二)

1.多執行緒死鎖 1.1什麼是多執行緒死鎖? 同步中巢狀同步,導致鎖無法釋放 程式碼示例: class Thread009 implements Runnable { private int trainCount = 100; private Object

java併發程式設計一一執行執行安全(一)

1.什麼是執行緒安全? 1.1為什麼有執行緒安全問題? 當多個執行緒同時共享同一個全域性變臉或靜態變數,做寫的操作時,可能會發生資料衝突的問題, 也就是執行緒安全的問題。但是做讀操作是不會發生資料衝突問題。 舉例:現在有100張火車票,有兩個視窗同時搶火車票,用多執行緒模擬搶

java併發程式設計一一執行基礎快速入門

1.執行緒與程序的區別 每個正在系統上執行的程式都是一個程序。每個程序包含一到多個執行緒。執行緒是一組指令的集合,或者是程式的特殊段,他可以在程式裡獨立執行。也可以把它理解為程式碼執行的上下文。 所以執行緒基本是輕量級的程序,它負責在單個程式裡執行任務。通常有作業系統負責多個執行緒

銀行業務系統(c/s架構、socket網路程式設計執行

1、功能要求 包括兩類使用者:管理人員和普通使用者(本文只寫了普通使用者程式) 普通使用者功能:登入登出、存取款、轉賬、查詢餘額 2、技術要求 要求用到多程序多執行緒 要求同時允許多個使用者操作(因為沒有註冊賬號功能,且只初始化了兩個賬號資訊,所以同時只能允許兩個賬號線上)

Python併發程式設計執行使用

目錄 一 開啟執行緒的兩種方式 二 在一個程序下開啟多個執行緒與在一個程序下開啟多個子程序的區別 三 練習 四 執行緒相關的其他方法 五 守護執行緒 六 Python GIL(Global Interpreter Lock) 七 同步鎖 八 死鎖現象

Java併發程式設計 HashMap執行不安全

我想在平時的多執行緒程式設計中,容器的使用是很普遍的,但是你有沒有考慮過有些容器是不安全的,如Haspmap、ArrayList。這裡講解一下Hashmap不安去體現在哪裡。 插入時不安全: 如果有兩個執行緒A和B,都進行插入資料,剛好經過雜湊計算後得到的雜湊碼是一樣的,即插入的

Java學習筆記——執行

多執行緒程式設計 程式: 程序:一個程式執行就會產生一個程序 執行緒:程序的執行流程,一個程序至少有一個執行緒,稱為主執行緒 如:QQ聊著天,同時在聽音樂 一個程序可以有多個執行緒,多個執行緒共享同一個程序的資源 執行緒類:Tread 多執行緒程式設計: 方式一:繼承Thread (1)&n