public static void Client()
{
Socket socket = null;? ? //實現(xiàn)客戶端套接字(也可以就叫“套接字”)
OutputStream output = null; ? ? ? ? //輸出流
try {
socket = new Socket(InetAddress.getLocalHost(),8888); ? ? ? ? ?/*套接字的實例化,可以使默認(rèn)的套接字,但是由于在通信中要知道對方的端口和IP等地址值信息所以一般需要定義
output = socket.getOutputStream(); ? ? ? ?//套接字類中一般有方法產(chǎn)生輸入流和輸出流
output.write("你是我額客戶端".getBytes());//寫入內(nèi)容可以使用Scanner類的控制臺輸入。?
output.flush(); ? ? ? ? ? ? ? ? ? ? ? ? ?//輸出流中一般在使用后需要清空通道(flush()方法的作用)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(socket != null)
try {
socket.close(); ? ? ? ? ? ? ? ? ? ? ? ? ? //套接字同流一樣需要關(guān)閉
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
///服務(wù)端
public static void Server()
{
ServerSocket serversocket=null; ? ? ? ? ? //接收端也就是服務(wù)端一般需要一個是接收套接字的類
try {
serversocket = new ServerSocket(8888); ? ? ?//實例化是要得到確定的端口號或者IP號,以保證在三次握手過程中能夠連接
Socket socket = serversocket.accept(); ? ?//得到發(fā)送過來的套接字類
InputStream input = socket.getInputStream();
byte[] arr = new byte[10];
int length;
while((length = input.read(arr)) != -1)//讀取信息
{
String str = new String(arr,0,length);
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
serversocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}