A. 速求用java語言寫聊天室的源代碼
【ClientSocketDemo.java 客戶端Java源代碼】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//聲明客戶端Socket對象socket
Socket socket = null;
//聲明客戶器端數據輸入輸出流
DataInputStream in;
DataOutputStream out;
//聲明字元串數組對象response,用於存儲從伺服器接收到的信息
String response[];
//執行過程中,沒有參數時的構造方法,本地伺服器在本地,取默認埠10745
public ClientSocketDemo()
{
try
{
//創建客戶端socket,伺服器地址取本地,埠號為10745
socket = new Socket("localhost",10745);
//創建客戶端數據輸入輸出流,用於對伺服器端發送或接收數據
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//獲取客戶端地址及埠號
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向伺服器發送數據
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//從伺服器接收數據
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//執行過程中,有一個參數時的構造方法,參數指定伺服器地址,取默認埠10745
public ClientSocketDemo(String hostname)
{
try
{
//創建客戶端socket,hostname參數指定伺服器地址,埠號為10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//執行過程中,有兩個個參數時的構造方法,第一個參數hostname指定伺服器地址
//第一個參數serverPort指定伺服器埠號
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 伺服器端Java源代碼】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//聲明ServerSocket類對象
ServerSocket serverSocket;
//聲明並初始化伺服器端監聽埠號常量
public static final int PORT = 10745;
//聲明伺服器端數據輸入輸出流
DataInputStream in;
DataOutputStream out;
//聲明InetAddress類對象ip,用於獲取伺服器地址及埠號等信息
InetAddress ip = null;
//聲明字元串數組對象request,用於存儲從客戶端發送來的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字元串數組
try
{
//獲取本地伺服器地址信息
ip = InetAddress.getLocalHost();
//以PORT為服務埠號,創建serverSocket對象以監聽該埠上的連接
serverSocket = new ServerSocket(PORT);
//創建Socket類的對象socket,用於保存連接到伺服器的客戶端socket對象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//創建伺服器端數據輸入輸出流,用於對客戶端接收或發送數據
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客戶端發送來的數據信息,並顯示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客戶端發送數據
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}
B. java中如何實現從客戶端發送文件到伺服器端
伺服器端源碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* 文件名:ServerReceive.java
* 實現功能:作為伺服器接收客戶端發送的文件
*
* 具體實現過程:
* 1、建立SocketServer,等待客戶端的連接
* 2、當有客戶端連接的時候,按照雙方的約定,這時要讀取一行數據
* 其中保存客戶端要發送的文件名和文件大小信息
* 3、根據文件名在本地創建文件,並建立好流通信
* 4、循環接收數據包,將數據包寫入文件
* 5、當接收數據的長度等於提前文件發過來的文件長度,即表示文件接收完畢,關閉文件
* 6、文件接收工作結束
public class ServerReceive {
public static void main(String[] args) {
/**與伺服器建立連接的通信句柄*/
ServerSocket ss = null;
Socket s = null;
/**定義用於在接收後在本地創建的文件對象和文件輸出流對象*/
File file = null;
FileOutputStream fos = null;
/**定義輸入流,使用socket的inputStream對數據包進行輸入*/
InputStream is = null;
/**定義byte數組來作為數據包的存儲數據包*/
byte[] buffer = new byte[4096 * 5];
/**用來接收文件發送請求的字元串*/
String comm = null;
/**建立socekt通信,等待伺服器進行連接*/
try {
ss = new ServerSocket(4004);
s = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
/**讀取一行客戶端發送過來的約定信息*/
try {
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
comm = br.readLine();
} catch (IOException e) {
System.out.println("伺服器與客戶端斷開連接");
}
/**開始解析客戶端發送過來的請求命令*/
int index = comm.indexOf("/#");
/**判斷協議是否為發送文件的協議*/
String xieyi = comm.substring(0, index);
if(!xieyi.equals("111")){
System.out.println("伺服器收到的協議碼不正確");
return;
}
/**解析出文件的名字和大小*/
comm = comm.substring(index + 2);
index = comm.indexOf("/#");
String filename = comm.substring(0, index).trim();
String filesize = comm.substring(index + 2).trim();
/**創建空文件,用來進行接收文件*/
file = new File(filename);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("伺服器端創建文件失敗");
}
}else{
/**在此也可以詢問是否覆蓋*/
System.out.println("本路徑已存在相同文件,進行覆蓋");
}
/**【以上就是客戶端代碼中寫到的伺服器的准備部分】*/
/**
* 伺服器接收文件的關鍵代碼*/
try {
/**將文件包裝到文件輸出流對象中*/
fos = new FileOutputStream(file);
long file_size = Long.parseLong(filesize);
is = s.getInputStream();
/**size為每次接收數據包的長度*/
int size = 0;
/**count用來記錄已接收到文件的長度*/
long count = 0;
/**使用while循環接收數據包*/
while(count < file_size){
/**從輸入流中讀取一個數據包*/
size = is.read(buffer);
/**將剛剛讀取的數據包寫到本地文件中去*/
fos.write(buffer, 0, size);
fos.flush();
/**將已接收到文件的長度+size*/
count += size;
System.out.println("伺服器端接收到數據包,大小為" + size);
}
} catch (FileNotFoundException e) {
System.out.println("伺服器寫文件失敗");
} catch (IOException e) {
System.out.println("伺服器:客戶端斷開連接");
}finally{
/**
* 將打開的文件關閉
* 如有需要,也可以在此關閉socket連接
* */
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}//catch (IOException e)
}//finally
}//public static void main(String[] args)
}//public class ServerReceive
客戶端源碼:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* 文件名:ClientSend.java
* 實現功能:作為客戶端向伺服器發送一個文件
*
* 具體實現過程:
* 1、建立與伺服器端的連接,IP:127.0.0.1, port:4004
* 2、將文件的名字和大小通過自定義的文件傳輸協議,發送到伺服器
* 3、循環讀取本地文件,將文件打包發送到數據輸出流中
* 4、關閉文件,結束傳輸
*
* */
public class ClientSend {
public static void main(String[] args) {
/**與伺服器建立連接的通信句柄*/
Socket s = null;
/**定義文件對象,即為要發送的文件
* 如果使用絕對路徑,不要忘記使用'/'和'\'的區別
* 具體區別,請讀者自行查詢
* */
File sendfile = new File("API.CHM");
/**定義文件輸入流,用來打開、讀取即將要發送的文件*/
FileInputStream fis = null;
/**定義byte數組來作為數據包的存儲數據包*/
byte[] buffer = new byte[4096 * 5];
/**定義輸出流,使用socket的outputStream對數據包進行輸出*/
OutputStream os = null;
/**檢查要發送的文件是否存在*/
if(!sendfile.exists()){
System.out.println("客戶端:要發送的文件不存在");
return;
}
/**與伺服器建立連接*/
try {
s = new Socket("127.0.0.1", 4004);
}catch (IOException e) {
System.out.println("未連接到伺服器");
}
/**用文件對象初始化fis對象
* 以便於可以提取出文件的大小
* */
try {
fis = new FileInputStream(sendfile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
/**首先先向伺服器發送關於文件的信息,以便於伺服器進行接收的相關准備工作
* 具體的准備工作,請查看伺服器代碼。
*
* 發送的內容包括:發送文件協議碼(此處為111)/#文件名(帶後綴名)/#文件大小
* */
try {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("111/#" + sendfile.getName() + "/#" + fis.available());
ps.flush();
} catch (IOException e) {
System.out.println("伺服器連接中斷");
}
/**
* 此處睡眠2s,等待伺服器把相關的工作準備好
* 也是為了保證網路的延遲
* 讀者可自行選擇添加此代碼
* */
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
/**之前的准備工作結束之後
* 下面就是文件傳輸的關鍵代碼
* */
try {
/**獲取socket的OutputStream,以便向其中寫入數據包*/
os = s.getOutputStream();
/** size 用來記錄每次讀取文件的大小*/
int size = 0;
/**使用while循環讀取文件,直到文件讀取結束*/
while((size = fis.read(buffer)) != -1){
System.out.println("客戶端發送數據包,大小為" + size);
/**向輸出流中寫入剛剛讀到的數據包*/
os.write(buffer, 0, size);
/**刷新一下*/
os.flush();
}
} catch (FileNotFoundException e) {
System.out.println("客戶端讀取文件出錯");
} catch (IOException e) {
System.out.println("客戶端輸出文件出錯");
}finally{
/**
* 將打開的文件關閉
* 如有需要,也可以在此關閉socket連接
* */
try {
if(fis != null)
fis.close();
} catch (IOException e) {
System.out.println("客戶端文件關閉出錯");
}//catch (IOException e)
}//finally
}//public static void main(String[] args)
}//public class ClientSend