導航:首頁 > 編程語言 > java客戶端與伺服器通信

java客戶端與伺服器通信

發布時間:2024-08-01 17:36:56

『壹』 java網路編程,怎樣在客戶端和伺服器間實現通信。

寫個簡單點的伺服器跟客服端就行了我寫了個很簡單的,只能在一個客戶端跟一個伺服器通信,在控制台輸入下面這個是伺服器import java.io.*;
import java.net.*;
import java.util.Scanner;public class Server
{
public static void main(String[] args)
{
try {
ServerSocket server=new ServerSocket(8888);//定義客戶端的埠號
Socket client=server.accept();//定義一個Socket對象

InputStream is=client.getInputStream();//伺服器接受信息輸入流,也就是接受從伺服器段發送過來的消息
BufferedReader br=new BufferedReader(new InputStreamReader(is));//用bufferedreader包裝下輸入流

OutputStream os=client.getOutputStream();//這是用來給伺服器發送消息的輸出流
PrintStream ps=new PrintStream(os);
Scanner scanner=new Scanner(System.in);//從鍵盤輸入字元串

boolean flag=true;//定義一個死循環,讓伺服器不停的接受從客戶端發送來的字元串
while(flag)
{
String s=br.readLine();//s是從客戶端接受到得字元串
System.out.println(s);

String s2=scanner.nextLine();//s2是寫給客戶端的字元串
ps.println(s2); //給客戶端發送你寫的東西
}
client.close();
} catch (IOException e) {//try 跟catch你不用管,這是用來處理異常的,就是固定格式

e.printStackTrace();
}
}
} 下面是客戶端import java.io.*;
import java.net.*;
import java.util.Scanner;public class Client
{ public static void main(String[] args)
{
try
{
Socket client=new Socket("192.168.--.--",8888);//IP地址是個字元串,埠號是個整數,這個埠號要跟前面你寫的那個一樣,還有IP地址,寫你的機器的IP地址

InputStream is=client.getInputStream();//這邊的兩個流跟上面伺服器的差不多的作用
BufferedReader bf=new BufferedReader(new InputStreamReader(is));

OutputStream os=client.getOutputStream();
PrintStream ps=new PrintStream(os);
Scanner scanner=new Scanner(System.in);
boolean flag=true;
while(flag)//這句話可以讓客戶端不停的說話
{
String s2=scanner.nextLine();
ps.println(s2);

String s=bf.readLine();
System.out.println(s); }

client.close();

}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
} }}

『貳』 JAVA程序完成伺服器和客戶端的SOCKET通訊,要求伺服器使用多線程接收和處理多個客戶端訪問請求

1. 客戶端程序
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
//向本機的4700埠發出客戶請求
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
String readline;
readline=sin.readLine(); //從系統標准輸入讀入一字元串
while(!readline.equals("bye")){
//若從標准輸入讀入的字元串為 "bye"則停止循環
os.println(readline);
//將從系統標准輸入讀入的字元串輸出到Server
os.flush();
//刷新輸出流,使Server馬上收到該字元串
System.out.println("Client:"+readline);
//在系統標准輸出上列印讀入的字元串
System.out.println("Server:"+is.readLine());
//從Server讀入一字元串,並列印到標准輸出上
readline=sin.readLine(); //從系統標准輸入讀入一字元串
} //繼續循環
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
}catch(Exception e) {
System.out.println("Error"+e); //出錯,則列印出錯信息
}
}
}
2. 伺服器端程序
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
//創建一個ServerSocket在埠4700監聽客戶請求
}catch(Exception e) {
System.out.println("can not listen to:"+e);
//出錯,列印出錯信息
}
Socket socket=null;
try{
socket=server.accept();
//使用accept()阻塞等待客戶請求,有客戶
//請求到來則產生一個Socket對象,並繼續執行
}catch(Exception e) {
System.out.println("Error."+e);
//出錯,列印出錯信息
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
PrintWriter os=newPrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
System.out.println("Client:"+is.readLine());
//在標准輸出上列印從客戶端讀入的字元串
line=sin.readLine();
//從標准輸入讀入一字元串
while(!line.equals("bye")){
//如果該字元串為 "bye",則停止循環
os.println(line);
//向客戶端輸出該字元串
os.flush();
//刷新輸出流,使Client馬上收到該字元串
System.out.println("Server:"+line);
//在系統標准輸出上列印讀入的字元串
System.out.println("Client:"+is.readLine());
//從Client讀入一字元串,並列印到標准輸出上
line=sin.readLine();
//從系統標准輸入讀入一字元串
} //繼續循環
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
server.close(); //關閉ServerSocket
}catch(Exception e){
System.out.println("Error:"+e);
//出錯,列印出錯信息
}
}}

『叄』 java多人聊天一般都是怎麼搭建的

Java多人聊天可以使用Java的Socket編程實現,主要的思路是:使用伺服器來維護所有客戶端的連接,並將客戶端之間的聊天信息進行轉發。巧稿歲

具體的實現步驟如下:

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

public class ChatServer {

private ServerSocket serverSocket;

private ArrayList<ClientHandler> clients;

public ChatServer(int port) throws IOException {

serverSocket = new ServerSocket(port);

clients = new ArrayList<ClientHandler>();

System.out.println("伺服器已啟動,等敬差待客戶端連接...");

}

public void start() throws IOException {

while (true) {

Socket socket = serverSocket.accept();

ClientHandler client = new ClientHandler(socket, this);

clients.add(client);

client.start();

}

}

public void broadcast(String message) {

for (ClientHandler client : clients) {

client.sendMessage(message);

}

}

public void removeClient(ClientHandler client) {

clients.remove(client);

}

public static void main(String[] args) throws IOException {

ChatServer server = new ChatServer(12345);

server.start();

}

}

客戶端:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

public class ChatClient {

private Socket socket;

private BufferedReader reader;

private PrintWriter writer;

private String name;

public ChatClient(String serverAddress, int port, String name) throws IOException {

socket = new Socket(serverAddress, port);

reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

writer = new PrintWriter(socket.getOutputStream(), true);

this.name = name;

}

public void start() throws IOException {

System.out.println("歡迎來到聊天室!");

new Thread(new IncomingMessageHandler()).start();

new Thread(new OutgoingMessageHandler()).start();

}

private class IncomingMessageHandler implements Runnable {

@Override

public void run() {

try {

while (true) {

String message = reader.readLine();

if (message == null) {

break;

}

System.out.println(message);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

close();

}

}

}

private class OutgoingMessageHandler implements Runnable {

@Override

public void run() {

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {

while (true) {

String message = reader.readLine();

if (message.equals("quit")) {

break;

}

writer.println(name + ": " + message);

}

} catch (IOException e) {

e.printStackTrace;

} finally {

close();

}

}

}

『肆』 JAVA TCP通信,客戶端給伺服器傳送JAVA對象通信出錯了,求各位大神指教

在java中用socket傳輸對象的時候,底層是把java對象序列化,然後以二進制數據進行傳輸的。socket的服務端和客戶端都需要有這個對象的聲明,比如客戶端發送的是com.client.MsgPackage對象,那麼這個對象的class文件必須在服務端的classpath中。否則就會是接收方接收了tcp的數據包,但是無法還原成對象。
底層要能把對象序列化,這個對象要實現一個可序列化的介面:java.io.Serializable。
類通過實現 java.io.Serializable
介面以啟用其序列化功能。未實現此介面的類將無法使其任何狀態序列化或反序列化。可序列化類的所有子類型本身都是可序列化的。序列化介面沒有方法或欄位,僅用於標識可序列化的語義。
writeObject 方法負責寫入特定類的對象的狀態,以便相應的 readObject 方法可以恢復它。通過調用
out.defaultWriteObject 可以調用保存 Object 的欄位的默認機制。該方法本身不需要涉及屬於其超類或子類的狀態。通過使用
writeObject 方法或使用 DataOutput 支持的用於基本數據類型的方法將各個欄位寫入 ObjectOutputStream,狀態可以被保存。
readObject 方法負責從流中讀取並恢復類欄位。它可以調用 in.defaultReadObject
來調用默認機制,以恢復對象的非靜態和非瞬態欄位。defaultReadObject
方法使用流中的信息來分配流中通過當前對象中相應指定欄位保存的對象的欄位。這用於處理類演化後需要添加新欄位的情形。該方法本身不需要涉及屬於其超類或子類的狀態。通過使用
writeObject 方法或使用 DataOutput 支持的用於基本數據類型的方法將各個欄位寫入 ObjectOutputStream,狀態可以被保存。

『伍』 java緗戠粶緙栫▼搴旇ユ庢牱鍦ㄥ㈡埛絝鍜屾湇鍔″櫒闂村疄鐜伴氫俊錛

浠ュ墠鍐欑殑錛岀収璐翠簡銆傘傘傛湇鍔″櫒絝錛歩mport java.awt.*;x0dx0aimport java.awt.event.WindowAdapter;x0dx0aimport java.awt.event.WindowEvent;x0dx0aimport java.io.*;x0dx0aimport java.net.*;/*6銆 閲囩敤UDP鍗忚錛岀紪鍐欎竴涓狫ava緗戠粶搴旂敤紼嬪簭錛岃ュ簲鐢ㄥ垎鏈嶅姟鍣ㄧ紼嬪簭鍜屽㈡埛絝紼嬪簭涓ら儴鍒嗐俓x0dx0a* 瀹㈡埛絝鎸囧畾涓涓鏈嶅姟鍣ㄤ笂鐨勬枃浠跺悕錛岃╂湇鍔″櫒鍙戝洖璇ユ枃浠剁殑鍐呭癸紝鎴栬呮彁紺烘枃浠朵笉瀛樺湪銆俓x0dx0a* 錛20鍒嗭級錛堟湇鍔$紼嬪簭鍜屽㈡埛絝紼嬪簭鍒嗗埆鍛藉悕涓篠erver.java鍜孋lient.java錛*/x0dx0apublic class N4BT6 extends Framex0dx0a{x0dx0aDatagramSocket socket ;x0dx0aDatagramPacket packet ;byte[] buf ;x0dx0aFile file ;x0dx0aFileInputStream input;x0dx0aString message = "璇ユ枃浠朵笉瀛樺湪";x0dx0aTextArea text;x0dx0apublic N4BT6(String title)x0dx0a{x0dx0asuper(title);x0dx0atext = new TextArea(6,4);x0dx0aadd(text);x0dx0asetSize(400, 300);x0dx0asetVisible(true);x0dx0aaddWindowListener(new WindowAdapter()x0dx0a{x0dx0apublic void windowClosing(WindowEvent e)x0dx0a{x0dx0adispose();x0dx0a}x0dx0a});x0dx0ax0dx0abuf = new byte[1024];x0dx0atryx0dx0a{x0dx0asocket = new DatagramSocket(1230);x0dx0apacket = new DatagramPacket(buf, buf.length);x0dx0asocket.receive(packet);x0dx0afile = new File(new String(packet.getData()));x0dx0asocket = new DatagramSocket();x0dx0a} x0dx0acatch (Exception e)x0dx0a{e.printStackTrace();x0dx0a}x0dx0ax0dx0aif(file.exists())x0dx0a{x0dx0atryx0dx0a{x0dx0abuf = new byte[(int)file.length()];x0dx0apacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);x0dx0ainput = new FileInputStream(file);x0dx0ainput.read(buf);x0dx0asocket.send(packet);x0dx0a}x0dx0acatch (IOException e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0aelsex0dx0a{x0dx0atryx0dx0a{x0dx0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,x0dx0aInetAddress.getLocalHost(),1234);x0dx0asocket.send(packet);x0dx0a}x0dx0acatch (Exception e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0ax0dx0a}x0dx0apublic static void main(String[] args)x0dx0a{x0dx0anew N4BT6("Server");x0dx0a}x0dx0a}x0dx0a瀹㈡埛絝錛歩mport java.awt.*;x0dx0aimport java.awt.event.*;x0dx0aimport java.net.DatagramPacket;x0dx0aimport java.net.DatagramSocket;x0dx0aimport java.net.InetAddress;public class N4BT6_2 extends Framex0dx0a{x0dx0aTextArea text;x0dx0aString message = "Q.txt";x0dx0aDatagramSocket socket ;x0dx0aDatagramPacket packet;x0dx0abyte[] buf;x0dx0apublic N4BT6_2(String title)x0dx0a{x0dx0asuper(title);x0dx0atext = new TextArea(6,4);x0dx0aadd(text);x0dx0asetSize(400, 300);x0dx0asetVisible(true);x0dx0aaddWindowListener(new WindowAdapter()x0dx0a{x0dx0apublic void windowClosing(WindowEvent e)x0dx0a{x0dx0adispose();x0dx0a}x0dx0a});x0dx0atryx0dx0a{x0dx0ax0dx0asocket = new DatagramSocket();x0dx0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,x0dx0aInetAddress.getLocalHost(),1230);x0dx0asocket.send(packet);x0dx0a}x0dx0acatch (Exception e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0ax0dx0atryx0dx0a{x0dx0abuf = new byte[1024];x0dx0asocket = new DatagramSocket(1234);x0dx0apacket = new DatagramPacket(buf,buf.length);x0dx0asocket.receive(packet);x0dx0atext.append(new String(buf));x0dx0a}x0dx0acatch (Exception e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0apublic static void main(String[] args)x0dx0a{x0dx0anew N4BT6_2("Client");x0dx0a}x0dx0a}

『陸』 用Java socket 實現客戶端與伺服器之間的數據的發送與接受。。。雙向的

下面是一個簡單的通訊實例,進行Server和Client之間的文件傳輸。。如果是簡單的文本傳輸的話簡化掉文本操作的內容即可。。

1.伺服器端

package sterning;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
int port = 8821;

void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 選擇進行傳輸的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);

System.out.println("文件長度:" + (int) fi.length());

// public Socket accept() throws
// IOException偵聽並接受到此套接字的連接。此方法在進行連接之前一直阻塞。

s = ss.accept();
System.out.println("建立socket鏈接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//將文件名及長度傳給客戶端。這里要真正適用所有平台,例如中文名的處理,還需要加工,具體可以參見Think In Java 4th里有現成的代碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關閉socket鏈接哦,不然客戶端會等待server的數據過來,
// 直到socket超時,導致數據不完整。
fis.close();
s.close();
System.out.println("文件傳輸完成");
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String arg[]) {
new ServerTest().start();
}
}

2.socket的Util輔助類

package sterning;

import java.net.*;
import java.io.*;

public class ClientSocket {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}

/** *//**
* 創建socket連接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}

public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}

public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}

public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {

}
}
}

3.客戶端

package sterning;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class ClientTest {
private ClientSocket cs = null;

private String ip = "localhost";// 設置成伺服器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("連接伺服器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("連接伺服器失敗!" + "\n");
return false;
}

}

private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("發送消息失敗!" + "\n");
}
}

private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息緩存錯誤\n");
return;
}

try {
//本地保存路徑,文件名會自動從伺服器端繼承而來。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;

savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(newBufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();

System.out.println("文件的長度為:" + len + "\n");
System.out.println("開始接收文件!" + "\n");

while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面進度條本為圖形界面的prograssBar做的,這里如果是打文件,可能會重復列印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存為" + savePath + "\n");

fileOut.close();
} catch (Exception e) {
System.out.println("接收消息錯誤" + "\n");
return;
}
}

public static void main(String arg[]) {
new ClientTest();
}
}

閱讀全文

與java客戶端與伺服器通信相關的資料

熱點內容
要我蘋果賬號密碼忘記了怎麼辦 瀏覽:578
快快卡在配置游戲文件 瀏覽:393
數據包重發時間怎麼調整 瀏覽:882
youtubeapp怎麼下載 瀏覽:366
編程檢測是什麼 瀏覽:753
網路攝像機的傳輸距離 瀏覽:941
超值貓qq群購秒殺群 瀏覽:138
pdf文件能備注嗎 瀏覽:174
html可視化數據源碼在哪裡 瀏覽:387
adobereader專用卸載工具 瀏覽:28
vivo手機數據如何備份 瀏覽:888
ithmb文件轉換器 瀏覽:66
看病找什麼網站好 瀏覽:579
linux如何查看文件系統 瀏覽:581
linux統計點頻率 瀏覽:627
全民泡泡大戰安琪兒升級 瀏覽:620
編程scratch如何保存 瀏覽:750
aspnetmvc傳json 瀏覽:132
如何下載看神片的狐狸視頻app 瀏覽:579
怎樣將木紋文件添加到cad 瀏覽:223

友情鏈接