導航:首頁 > 編程語言 > javasocket通信實例

javasocket通信實例

發布時間:2023-07-08 00:56:56

1. 用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();
}
}

2. 誰能給一個 Qt 跟 java 用socket通訊的例子,要求java 做服務端,qt 做客戶端,要求雙方都能實時顯示對方發過

提供一個聊天功能的給你
import java.net.*;
import java.io.*;

class My1 extends Thread
{
private Socket skt;

public My1(Socket skt)
{
this.skt = skt;
}

public void run()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));

for(;;)
{
if(br.readLine()==null) {break;}
System.out.println(br.readLine()); // 阻塞
}
}
catch(Exception e)
{
System.out.println("對方斷線!");
}
}
}

class My2 extends Thread
{
private Socket skt;

public My2(Socket skt)
{
this.skt = skt;
}

public void run()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(skt.getOutputStream());

for(;;)
{
pw.println("姓名====>:"+br.readLine()); // 阻塞
pw.flush();
}
}
catch(Exception e)
{
System.out.println("對方斷線!");
}
}
}

public class Good
{
public static void main(String[] args) throws Exception
{
//連接的目的是:獲得Socket對象
Socket skt;

System.out.print("請輸入<port> 或者:<ip>,<port> ");
// 先選擇角色
String[] ss = new BufferedReader(new InputStreamReader(System.in)).readLine().split(",");
if(ss.length==1)
skt = new ServerSocket(Integer.parseInt(ss[0])).accept();
else
skt = new Socket(ss[0], Integer.parseInt(ss[1]));

System.out.println("連接到:" + skt.getInetAddress().getHostAddress());
// 連接建立,角色消失

new My1(skt).start(); //讀網路
new My2(skt).start(); //讀鍵盤
}
}

3. 用JAVA編寫一個socket通信程序

埠監聽和建立管道。首先伺服器端綁定監聽埠,然後客戶端socket連接到這個埠,控制台輸入的字元串都會被在這個埠監聽的伺服器接收到。

4. 如何干凈的實現Android/Java Socket 長連接通信

Java Socket通信有很多的時候需要我們不斷的學習。方面效率雖然不及C與C++但它以靈活語言優勢,為大家廣為使用。 本文就對在使用java做通信方面程序時候應改注意問題做以說明。1.長連接、短鏈接只是針對客戶端而言,伺服器無所謂長、短;2.無論同步或者非同步通信,發送之後務必要又響應回復,確認收到,負責進行一定范圍內重發,例如重發三次;3.長連接伺服器與客戶端之間務必需要心跳探測,由客戶端主動發起;4.短連接伺服器通用代碼:
package com.biesan.sms.gate.unioncom.communication;
import com.biesan.commons.Constants;
import com.biesan.commons.util.CodeUtil;
import com.biesan.sms.gate.unioncom.data.*;
import com.biesan.sms.gate.unioncom.util.GateInfo;
import java.net.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
import spApi.*;
public class UnioncomDeliver extends Thread {
// stop flag
private boolean unInterrupt = true;
private boolean unErr = true;
//private boolean closeSocketFlag = false;
// server socket
private ServerSocket serverSo = null;
// current socket
private Socket so = null
private OutputStream output = null;
private InputStream input = null;
// gate command
private SGIP_Command tmpCmd = null;
private SGIP_Command cmd = null;
private Bind bind = null;
private BindResp bindResp = null;
//private Unbind unBind = null;
private UnbindResp unBindResp = null;
private boolean unAcceptErrorFlag = true;
Logger unioncomLog = Logger.getLogger(Unioncom
Deliver.class.getName());
public UnioncomDeliver() {
}
public void run() {
unioncomLog.info("Start...");
while (unInterrupt) {
this.initServer();
this.startServices();
while (this.unAcceptErrorFlag) {
try {
//接受連接請求
unioncomLog.info("before accept connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
this.acceptConnection();
unioncomLog.info("after accept connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
while (unErr) {
cmd = new Command();
unioncomLog.info("before read command from stream
........... FreeMemroy: " + Runtime.getRuntime().
freeMemory());
tmpCmd = cmd.read(input);
unioncomLog.info("after read command from stream " +
getCommandString(cmd.getCommandID()) + " FreeMemroy: " +
Runtime.getRuntime().freeMemory());
if (tmpCmd == null) {
unErr = false;
break;
}
switch (cmd.getCommandID()) {
// biad ready communication
case SGIP_Command.ID_SGIP_BIND: {
this.dealBind();
break;
}// exit bind
case SGIP_Command.ID_SGIP_UNBIND: {
this.dealUnBind();
unioncomLog.info("after unbind connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
break;
}// deliver
....
default : //錯誤的命令字
break;
}// switch
}// while(unErr)
} catch (Exception e) {
unioncomLog.error("Unioncom Recv Service Error"
+ e.getMessage());
} finally {
if (this.so != null) {
this.closeSocket();
}
this.unErr = true;
}
}// while (this.unAcceptErrorFlag)
try {
this.closeServerSocket();
sleep(200);// sleep
} catch (InterruptedException ie) {
}
}// while(unInterrupt)
}
private String getCommandString(int cmd){
switch (cmd) {
// biad ready communication
case SGIP_Command.ID_SGIP_BIND: {
return " BIND COMMAND ";
}// exit bind
case SGIP_Command.ID_SGIP_UNBIND: {
return " UNBIND COMMAND ";
}// deliver
case ...
default:
return " UNKNOWN COMMAND";
}
}
private void dealBind() {
try {
bind = new Bind(tmpCmd);
if (bind.readbody() != 0) {
unioncomLog.warn("Read Bind error");
this.unErr = false;
}
bindResp = new BindResp(tmpCmd.getMsgHead());
bindResp.SetResult(0);
bindResp.write(output);
unioncomLog.debug("Bind success!");
} catch (Exception e) {
unioncomLog.error("Dela Union Recv Bind Error!" +
e.getMessage());
this.unErr = false;
}
}
private void dealUnBind() {
try {
//unBind = (Unbind) tmpCmd;
unBindResp = new UnbindResp(tmpCmd.getMsgHead());
unBindResp.write(output);
unioncomLog.debug("UnBind success!");
} catch (Exception e) {
unioncomLog.warn("Unbind error!" + e.getMessage());
}
this.unErr = false;
}
private void startServices() {
boolean unStartServices = true;
while (unStartServices) {
try {
serverSo = new ServerSocket(ugInfo.getLocalServerPort(), 5,
InetAddress.getByName(ugInfo.getLocalIpAdd()));
//serverSo.setSoTimeout(60000);
unStartServices = false;
unioncomLog.info("Create union recv socket Ok!");
} catch (IOException e) {
unioncomLog.warn("Create union recv socket error!"
+ e.getMessage());
unStartServices = true;
UnioncomSubmit.thrSlp(3000);
}
}
}
private void acceptConnection() {
// Accept 失敗
try {
so = serverSo.accept();
so.setSoTimeout(10000);
} catch (Exception e) {
unioncomLog.warn("Accept Error!" + e.getMessage());
this.closeServerSocket();
this.unAcceptErrorFlag = false;
this.unErr=false;
}
// Accept成功
try {
input = so.getInputStream();
output = so.getOutputStream();
} catch (IOException e) {
unioncomLog.warn("Get I/O stream Error!" + e.getMessage());
this.closeService();
this.unAcceptErrorFlag = false;
this.unErr=false;
}
}
private void closeSocket() {
try {
so.close();
unioncomLog.info("Socket Close Success!!!");
} catch (Exception e) {
unioncomLog.error("Socket Close Failure!!!" + e.getMessage());
}
}
private void closeServerSocket() {
try {
serverSo.close();
unioncomLog.info("ServerSocket Close Success!!!");
} catch (Exception e) {
unioncomLog
.error("ServerSocket Close Failure!!!" + e.getMessage());
}
}
private void closeService() {
this.closeSocket();
this.closeServerSocket();
}
private void initServer() {
this.bind = null;
this.bindResp = null;
//this.unBind = null;
this.unBindResp = null;
this.tmpCmd = null;
this.cmd = null;
this.serverSo = null;
this.so = null;
this.output = null;
this.input = null;
this.unErr = true;
//this.closeSocketFlag = false;
unioncomLog.info("Memory***==="
+ java.lang.Runtime.getRuntime().freeMemory());
}
public synchronized void requireStop() {
this.unInterrupt = false;
unioncomLog.info("Requre interrupt!!!");
}
public String convertMsgContentCoding
(int msgCoding, byte[] msgContent) {
String deliverContent = null;
try {
if (msgContent != null) {
if (msgCoding == 8) { // 處理ucs32編碼
deliverContent = new String(msgContent,
"UnicodeBigUnmarked");
} else if (msgCoding == 0) { // 處理ASCII編碼
deliverContent = new String(msgContent, "ASCII");
} else if (msgCoding == 4) { // 處理binary編碼
deliverContent = new String(msgContent);
} else if (msgCoding == 15) { // 處理GBK編碼
deliverContent = new String(msgContent, "GBK");
// 處理DELIVER數據包的簡訊息ID
} else {
unioncomLog.error("編碼格式錯誤!");
return "";
}
} else
return "";
return deliverContent;
} catch (UnsupportedEncodingException ex) {
unioncomLog.error("deal content error!" +
ex.getMessage());
return "";
}
}
}

5. java socket一對多通信如何實現

伺服器端發送消息,你要知道給哪個客戶端發,應該是將所有的客戶端連接都放在數組里,然後遍歷數組發送
參考下吧: http://wenku..com/view/a9598469c5da50e2524d7f82.html

6. java socket伺服器怎麼給客戶端發信息

伺服器端和客戶端都是通過SOCKET來進行通信的,首先產生一個
socket實例,通過這個實例,伺服器端調用accept這個方法接收來自客戶端發送的信息.但是在產生socket實例的時候必須初始化一個埠.用來負責接受客戶端的請求!
客戶端要給伺服器發送消息也必須產生一個socket實例,初始化的時候必須指定伺服器的IP地址,並且指定服務接收的埠號,這樣客戶端才能找到伺服器要接收的地方,找到地方就可以發送過去了。和你寫信一樣。找到地址
BufferedReader
in
=
new
BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter
out
=
new
PrintWriter(socket.getOutputStream());
BufferedReader
wt
=
new
BufferedReader(new
InputStreamReader(System.in));
這個只是用來獲取一個從鍵盤的一個流.傳送給伺服器端的數據都是通過流來表示的。意思是是鍵盤輸入的一個位元組轉化成字元流.並輸出或者寫入!

7. 用JAVA寫一個SOCKET 接收TCP發來的消息

public class TalkServer{

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);

//出錯,列印出錯信息

}

}

}

閱讀全文

與javasocket通信實例相關的資料

熱點內容
2021三支一扶報名數據在哪裡看 瀏覽:914
網路未備案怎麼打得開 瀏覽:987
計算機程序用什麼編程語言 瀏覽:324
linux入門常用命令 瀏覽:497
江寧區哪裡有數控編程培訓 瀏覽:778
java寫一個shape形狀類 瀏覽:744
win7如何設置word背景顏色 瀏覽:484
如何創造電腦編程語言 瀏覽:56
昂達平板電腦圖形密碼忘記怎麼辦 瀏覽:92
組織文件內容是什麼 瀏覽:183
0基礎如何學習智能編程 瀏覽:366
java程序員全攻略下載 瀏覽:715
網路逆向教程 瀏覽:135
iso文件如何重裝系統 瀏覽:750
ghost鏡像文件路徑如何恢復 瀏覽:832
搭建網站需要多少錢啊 瀏覽:599
編程貓怎麼設置背景亮度 瀏覽:177
qq文件破損 瀏覽:414
javapoi配置 瀏覽:608
編程怎麼寫數據圖案同步 瀏覽:308

友情鏈接