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