例子是學(xué)習編程的法寶。你在學(xué)習java Socket 嗎?看看下面的這個(gè)例子吧!
實(shí)現Client端功能的ClientApp.java原文件:
import java.net.*;
import java.io.*;
import java.lang.*;
public class ClientApp
{
public static void main(String args[])
{
try
{
//創(chuàng )建通訊并且和主機Rock連接
Socket cSocket=new Socket("192.168.100.188",8018);
//打開(kāi)這個(gè)Socket的輸入/輸出流
OutputStream os=cSocket.getOutputStream();
DataInputStream is=new DataInputStream(cSocket.getInputStream());
int c;
boolean flag=true;
String responseline;
while(flag)
{
//從標準輸入輸出接受字符并且寫(xiě)如系統
while((c=System.in.read())!=-1)
{
os.write((byte)c);
if(c==‘‘\n‘‘)
{
os.flush();
//將程序阻塞,直到回答信息被收到后將他們在標準輸出上顯示出來(lái)
responseline=is.readLine();
System.out.println("Message is:"+responseline);
}
}
}
os.close();
is.close();
cSocket.close();
}
catch(Exception e)
{
System.out.println("Exception :"+ e.getMessage());
}
}
}
實(shí)現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)
{
//當客戶(hù)端輸入stop的時(shí)候服務(wù)器程序運行終止!
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(); //將信息發(fā)送到客戶(hù)端
break;
}
}
}
}
is.close();
os.close();
clientSocket.close();
}
sSocket.close();
}
catch(Exception e)
{
System.out.println("Exception :"+ e.getMessage());
}
}
}