java Socket 通訊的代碼例子

來源:互聯網
上載者:User

實現Client端功能的ClientApp.java原檔案:

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

public class ClientApp
{
public static void main(String args[])
{
try
{
//建立通訊並且和主機Rock串連
Socket cSocket=new Socket("192.168.100.188",8018);
//開啟這個Socket的輸入/輸出流
OutputStream os=cSocket.getOutputStream();
DataInputStream is=new DataInputStream(cSocket.getInputStream());

int c;
boolean flag=true;

String responseline;

while(flag)
{
//從標準輸入輸出接受字元並且寫如系統
while((c=System.in.read())!=-1)
{
os.write((byte)c);
if(c=='\n')
{
os.flush();
//將程式阻塞,直到回答資訊被收到後將他們在標準輸出上顯示出來
responseline=is.readLine();
System.out.println("Message is:"+responseline);
}
}
}
os.close();
is.close();
cSocket.close();

}
catch(Exception e)
{
System.out.println("Exception :"+ e.getMessage());
}
}
}


實現Server端功能的ServerApp.java原檔案:

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

public class ServerApp
{
public static void main(String args[])
{
try
{
boolean flag=true;
Socket clientSocket=null;
String inputLine;
int c;

ServerSocket sSocket=new ServerSocket(8018);
System.out.println("Server listen on:"+sSocket.getLocalPort());

while(flag)
{
clientSocket=sSocket.accept();
DataInputStream is= new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
OutputStream os=clientSocket.getOutputStream();

while((inputLine=is.readLine())!=null)
{
//當用戶端輸入stop的時候伺服器程式運行終止!
if(inputLine.equals("stop"))
{
flag=false;
break;
}
else
{
System.out.println(inputLine);

while((c=System.in.read())!=-1)
{
os.write((byte)c);
if(c=='\n')
{
os.flush(); //將資訊發送到用戶端
break;
}
}
}


}
is.close();
os.close();
clientSocket.close();

}
sSocket.close();
}
catch(Exception e)
{
System.out.println("Exception :"+ e.getMessage());
}
}
}






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.