網絡編程的基本模型就是客戶機到服務器模型
Java對這個模型的支持有很多種Api
=new Socket(InetAddress
上面的方法基本可以建立一條連線讓兩台計算機相互交流了
BufferedReader in=new BufferedReader(new InputStreamReader(server
PrintWriter out=new PrintWriter(server
上面兩句就是建立緩沖並把原始的字節流轉變為Unicode可以操作
服務方:
import java
import
public class MyServer {
public static void main(String[] args) throws IOException{
ServerSocket server=new ServerSocket(
Socket client=server
BufferedReader in=new BufferedReader(new InputStreamReader(client
PrintWriter out=new PrintWriter(client
while(true){
String str=in
System
out
out
if(str
break;
}
client
}
}
這個程序的主要目的在於服務器不斷接收客戶機所寫入的信息只到
客戶機代碼:
import
import java
public class Client{
static Socket server;
public static void main(String[] args)throws Exception{
server=new Socket(InetAddress
BufferedReader in=new BufferedReader(new InputStreamReader(server
PrintWriter out=new PrintWriter(server
BufferedReader wt=new BufferedReader(new InputStreamReader(System
while(true){
String str=wt
out
out
if(str
break;
}
System
}
server
}
}
客戶機代碼則是接受客戶鍵盤輸入
這個程序只是簡單的兩台計算機之間的通訊
其實
服務器:
import java
import
public class MyServer {
public static void main(String[] args) throws IOException{
ServerSocket server=new ServerSocket(
while(true){
Socket client=server
BufferedReader in=new BufferedReader(new InputStreamReader(client
PrintWriter out=new PrintWriter(client
while(true){
String str=in
System
out
out
if(str
break;
}
client
}
}
}
這裡僅僅只是加了一個外層的While循環
那麼下面的問題是如何使用線程
import
import java
public class MultiUser extends Thread{
private Socket client;
public MultiUser(Socket c){
this
}
public void run(){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(client
PrintWriter out=new PrintWriter(client
//Mutil User but can
while(true){
String str=in
System
out
out
if(str
break;
}
client
}catch(IOException ex){
}finally{
}
}
public static void main(String[] args)throws IOException{
ServerSocket server=new ServerSocket(
while(true){
//transfer location change Single User or Multi User
MultiUser mu=new MultiUser(server
mu
}
}
}
我的類直接從Thread類繼承了下來
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27013.html