java連接socket
java編程對於Socket之間的通信過程如下:
服務端往Socket的輸出流裡面寫東西,客戶端就可以通過Socket的輸入流讀取對應的內容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應的Socket輸出流裡面寫東西,然後服務端對應的Socket的輸入流就可以讀出對應的內容。下面來看一些服務端與客戶端通信的例子:
publicclassServer{
publicstaticvoidmain(Stringargs[])throwsIOException{
//為了簡單起見,所有的異常信息都往外拋
intport=8899;
//定義一個ServerSocket監聽在埠8899上
ServerSocketserver=newServerSocket(port);
//server嘗試接收其他Socket的連接請求,server的accept方法是阻塞式的
Socketsocket=server.accept();
//跟客戶端建立好連接之後,我們就可以獲取socket的InputStream,並從中讀取客戶端發過來的信息了。
Readerreader=newInputStreamReader(socket.getInputStream());
charchars[]=newchar[64];
intlen;
StringBuildersb=newStringBuilder();
while((len=reader.read(chars))!=-1){
sb.append(newString(chars,0,len));
}
System.out.println("fromclient:"+sb);
reader.close();
socket.close();
server.close();
}
}
客戶端代碼
Java代碼publicclassClient{
publicstaticvoidmain(Stringargs[])throwsException{
//為了簡單起見,所有的異常都直接往外拋
Stringhost="127.0.0.1";//要連接的服務端IP地址
intport=8899;//要連接的服務端對應的監聽埠
//與服務端建立連接
Socketclient=newSocket(host,port);
//建立連接後就可以往服務端寫數據了
Writerwriter=newOutputStreamWriter(client.getOutputStream());
writer.write("HelloServer.");
writer.flush();//寫完後要記得flush
writer.close();
client.close();
}
}
❷ 如何干凈的實現Android/Java Socket 長連接通信
JavaSocket通信有很多的時候需要我們不斷的學習。方面效率雖然不及C與C++但它以靈活語言優勢,為大家廣為使用。本文就對在使用java做通信方面程序時候應改注意問題做以說明。
1.長連接、短鏈接只是針對客戶端而言,伺服器無所謂長、短;
2.無論同步或者非同步通信,發送之後務必要又響應回復,確認收到,負責進行一定范圍內重發,例如重發三次;
3.長連接伺服器與客戶端之間務必需要心跳探測,由客戶端主動發起;
4.短連接伺服器通用代碼:
python">packagecom.biesan.sms.gate.unioncom.communication;
importcom.biesan.commons.Constants;
importcom.biesan.commons.util.CodeUtil;
importcom.biesan.sms.gate.unioncom.data.*;
importcom.biesan.sms.gate.unioncom.util.GateInfo;
importjava.net.*;
importjava.io.*;
importjava.util.*;
importorg.apache.log4j.*;
importspApi.*;
{
//stopflag
privatebooleanunInterrupt=true;
privatebooleanunErr=true;
//privatebooleancloseSocketFlag=false;
//serversocket
privateServerSocketserverSo=null;
//currentsocket
privateSocketso=null
privateOutputStreamoutput=null;
privateInputStreaminput=null;
//gatecommand
privateSGIP_CommandtmpCmd=null;
privateSGIP_Commandcmd=null;
privateBindbind=null;
privateBindRespbindResp=null;
//privateUnbinnBind=null;
privateUnbindRespunBindResp=null;
=true;
LoggerunioncomLog=Logger.getLogger(Unioncom
Deliver.class.getName());
publicUnioncomDeliver(){
}
publicvoidrun(){
unioncomLog.info("Start...");
while(unInterrupt){
this.initServer();
this.startServices();
while(this.unAcceptErrorFlag){
try{
//接受連接請求
unioncomLog.info("beforeacceptconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
this.acceptConnection();
unioncomLog.info("afteracceptconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
while(unErr){
cmd=newCommand();
unioncomLog.info("beforereadcommandfromstream
...........FreeMemroy:"+Runtime.getRuntime().
freeMemory());
tmpCmd=cmd.read(input);
unioncomLog.info("afterreadcommandfromstream"+
getCommandString(cmd.getCommandID())+"FreeMemroy:"+
Runtime.getRuntime().freeMemory());
if(tmpCmd==null){
unErr=false;
break;
}
switch(cmd.getCommandID()){
//biadreadycommunication
caseSGIP_Command.ID_SGIP_BIND:{
this.dealBind();
break;
}//exitbind
caseSGIP_Command.ID_SGIP_UNBIND:{
this.dealUnBind();
unioncomLog.info("afterunbindconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
break;
}//deliver
....
default://錯誤的命令字
break;
}//switch
}//while(unErr)
}catch(Exceptione){
unioncomLog.error("UnioncomRecvServiceError"
+e.getMessage());
}finally{
if(this.so!=null){
this.closeSocket();
}
this.unErr=true;
}
}//while(this.unAcceptErrorFlag)
try{
this.closeServerSocket();
sleep(200);//sleep
}catch(InterruptedExceptionie){
}
}//while(unInterrupt)
}
privateStringgetCommandString(intcmd){
switch(cmd){
//biadreadycommunication
caseSGIP_Command.ID_SGIP_BIND:{
return"BINDCOMMAND";
}//exitbind
caseSGIP_Command.ID_SGIP_UNBIND:{
return"UNBINDCOMMAND";
}//deliver
case...
default:
return"UNKNOWNCOMMAND";
}
}
privatevoiddealBind(){
try{
bind=newBind(tmpCmd);
if(bind.readbody()!=0){
unioncomLog.warn("ReadBinderror");
this.unErr=false;
}
bindResp=newBindResp(tmpCmd.getMsgHead());
bindResp.SetResult(0);
bindResp.write(output);
unioncomLog.debug("Bindsuccess!");
}catch(Exceptione){
unioncomLog.error("DelaUnionRecvBindError!"+
e.getMessage());
this.unErr=false;
}
}
privatevoiddealUnBind(){
try{
//unBind=(Unbind)tmpCmd;
unBindResp=newUnbindResp(tmpCmd.getMsgHead());
unBindResp.write(output);
unioncomLog.debug("UnBindsuccess!");
}catch(Exceptione){
unioncomLog.warn("Unbinderror!"+e.getMessage());
}
this.unErr=false;
}
privatevoidstartServices(){
booleanunStartServices=true;
while(unStartServices){
try{
serverSo=newServerSocket(ugInfo.getLocalServerPort(),5,
InetAddress.getByName(ugInfo.getLocalIpAdd()));
//serverSo.setSoTimeout(60000);
unStartServices=false;
unioncomLog.info("CreateunionrecvsocketOk!");
}catch(IOExceptione){
unioncomLog.warn("Createunionrecvsocketerror!"
+e.getMessage());
unStartServices=true;
UnioncomSubmit.thrSlp(3000);
}
}
}
privatevoidacceptConnection(){
//Accept失敗
try{
so=serverSo.accept();
so.setSoTimeout(10000);
}catch(Exceptione){
unioncomLog.warn("AcceptError!"+e.getMessage());
this.closeServerSocket();
this.unAcceptErrorFlag=false;
this.unErr=false;
}
//Accept成功
try{
input=so.getInputStream();
output=so.getOutputStream();
}catch(IOExceptione){
unioncomLog.warn("GetI/OstreamError!"+e.getMessage());
this.closeService();
this.unAcceptErrorFlag=false;
this.unErr=false;
}
}
privatevoidcloseSocket(){
try{
so.close();
unioncomLog.info("SocketCloseSuccess!!!");
}catch(Exceptione){
unioncomLog.error("SocketCloseFailure!!!"+e.getMessage());
}
}
privatevoidcloseServerSocket(){
try{
serverSo.close();
unioncomLog.info("ServerSocketCloseSuccess!!!");
}catch(Exceptione){
unioncomLog
.error("ServerSocketCloseFailure!!!"+e.getMessage());
}
}
privatevoidcloseService(){
this.closeSocket();
this.closeServerSocket();
}
privatevoidinitServer(){
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());
}
(){
this.unInterrupt=false;
unioncomLog.info("Requreinterrupt!!!");
}
(intmsgCoding,byte[]msgContent){
StringdeliverContent=null;
try{
if(msgContent!=null){
if(msgCoding==8){//處理ucs32編碼
deliverContent=newString(msgContent,
"UnicodeBigUnmarked");
}elseif(msgCoding==0){//處理ASCII編碼
deliverContent=newString(msgContent,"ASCII");
}elseif(msgCoding==4){//處理binary編碼
deliverContent=newString(msgContent);
}elseif(msgCoding==15){//處理GBK編碼
deliverContent=newString(msgContent,"GBK");
//處理DELIVER數據包的簡訊息ID
}else{
unioncomLog.error("編碼格式錯誤!");
return"";
}
}else
return"";
returndeliverContent;
}catch(){
unioncomLog.error("dealcontenterror!"+
ex.getMessage());
return"";
}
}
}
❸ java簡答題 如何創建socket連接的過程
java socket建立連接的過程如下:
socket
1、 首先調用Socket類的構造函數,以伺服器的指定的IP地址或指定的主機名和指定的埠號為參數,創建一個Socket流,在創建Socket流的過程中包含了向伺服器請求建立通訊連接的過程實現。
2、 建立了客戶端通訊Socket後。就可以使用Socket的方法getInputStream()和getOutputStream()來創建輸入/輸出流。這樣,使用Socket類後,網路輸入輸出也轉化為使用流對象的過程。
3、 使用輸入輸出流對象的相應方法讀寫位元組流數據,因為流連接著通訊所用的Socket,Socket又是和伺服器端建立連接的一個端點,因此數據將通過連接從伺服器得到或發向伺服器。這時我們就可以對位元組流數據按客戶端和伺服器之間的協議進行處理,完成雙方的通訊任務。
4、 待通訊任務完畢後,我們用流對象的close()方法來關閉用於網路通訊的輸入輸出流,在用Socket對象的close()方法來關閉Socket。
❹ 瘋狂Java講義:使用Socket進行通信[2]
程序清單 codes/ / /Client java
public class Client
{
public static void main(String[] args)
throws IOException
{
Socket socket = new Socket( )
//將Socket對應的輸入流包裝成BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(socket getInputStream()))
//進行普通IO操作
String line = br readLine()
System out println( 來自伺服器的數據 + line)
//關閉輸入流 socket
br close()
socket close()
}
}
上面程序中粗體字代碼是使用ServerSocket和Socket建立網路連接的代碼 斜體字代碼是通過Socket獲取輸入流 輸出流進行通信的代碼 通過程序不難看出 一旦使用ServerSocket Socket建立網路連接之後 程序通過網路通信與普通IO並沒有太大的區別
先運行上面程序中的Server類 將看到伺服器一直處於等待狀態 因為伺服器使用了死循環來接受來自客戶端的請求 再運行Client類 將可看到程序輸出 來自伺服器的數據 您好 您收到了伺服器的新年祝福! 這表明客戶端和伺服器端通信成功
上面程序為了突出通過ServerSocket和Socket建立連接 並通過底層IO流進行通信的主題 程序沒有進行異常處理 也沒有使用finally塊來關閉資源
實際應用中 程序可能不想讓執行網路連接 讀取伺服器數據的進程一直阻塞 而是希望當網路連接 讀取操作超過合理時間之後 系統自動認為該操作失敗 這個合理時間就是超時時長 Socket對象提供了一個setSoTimeout(int timeout)來設置超時時長 如下的代碼片段所示
Socket s = new Socket( )
//設置 秒之後即認為超時
s setSoTimeout( )
當我們為Socket對象指定了超時時長之後 如果在使用Socket進行讀 寫操作完成之前已經超出了該時間限制 那麼這些方法就會拋出SocketTimeoutException異常 程序可以對該異常進行捕捉 並進行適當處理 如下代碼所示
try
{
//使用Scanner來讀取網路輸入流中的數據
Scanner scan = new Scanner(s getInputStream())
//讀取一行字元
String line = scan nextLine()
…
}
//捕捉SocketTimeoutException異常
catch(SocketTimeoutException ex)
{
//對異常進行處理
…
}
假設程序需要為Socket連接伺服器時指定超時時長 即經過指定時間後 如果該Socket還未連接到遠程伺服器 則系統認為該Socket連接超時 但Socket的所有構造器里都沒有提供指定超時時長的參數 所以程序應該先創建一個無連接的Socket 再調用Socket的connect()方法來連接遠程伺服器 而connect方法就可以接受一個超時時長參數 如下代碼所示
//創建一個無連接的Socket
Socket s = new Socket()
//讓該Socket連接到遠程伺服器 如果經過 秒還沒有連接到 則認為連接超時
s connconnect(new InetAddress(host port) )
返回目錄 瘋狂Java講義
編輯推薦
Java程序性能優化 讓你的Java程序更快 更穩定
新手學Java 編程
Java程序設計培訓視頻教程
lishixin/Article/program/Java/hx/201311/27265
❺ java中用socket實現客戶端與服務端雙向連接問題
//服務端程序:
importjava.io.*;
importjava.net.*;
publicclassTCPServer{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPServer().init();
}
@SuppressWarnings("static-access")
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
ServerSocketserver=newServerSocket(1000);
Socketclient=null;
while(true){
try{
client=server.accept();
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
Stringmessage="";
while((len=bis.read(b))!=-1){
message=newString(b,0,len);
System.out.print("客戶端:"+client.getInetAddress().getLocalHost().getHostAddress()+"發來消息:"+message);
if("byte".equals(message.trim()))
client.close();
PrintWriterpw=newPrintWriter(client.getOutputStream(),true);
pw.println(message);
}
}catch(Exceptione){
System.err.println("客戶端:"+client.getInetAddress().getLocalHost().getHostAddress()+"已斷開連接!");
}
}
}
}
//客戶端程序:
importjava.io.*;
importjava.net.Socket;
{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPClient().init();
}
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
finalSocketclient=newSocket("127.0.0.1",1000);
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
Stringsend="";
while(true){
send=in.readLine();
PrintWriterout=newPrintWriter(client.getOutputStream(),true);
if(!"byte".equals(send.trim()))
out.println(send);
else{
out.println(send);
System.exit(0);
}
newThread(newTCPClient(){
@SuppressWarnings("static-access")
publicvoidrun(){
try{
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
while((len=bis.read(b))!=-1){
System.out.println("伺服器:"+client.getInetAddress().getLocalHost().getHostAddress()+"發來消息:"+newString(b,0,len).trim());
}
}catch(IOExceptione){
System.err.println("連接伺服器失敗!");
}
}
}).start();
}
}
publicvoidrun(){}
}
//伺服器測試結果:
客戶端:192.168.0.200發來消息:001 byte
客戶端:192.168.0.200發來消息:byte
客戶端:192.168.0.200 已斷開連接!
客戶端:192.168.0.200發來消息:adasd
客戶端:192.168.0.200 已斷開連接!
//客戶端測試結果:
---001號客戶端--
001byte
伺服器:192.168.0.200發來消息:001byte
byte //001禮貌說跟伺服器說byte
---002號客戶端--
adasd //002客戶端直接關閉程序
伺服器:192.168.0.200發來消息:adasd