服務器:
public class ClientDemo {
/**
* @param args
*/
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost",8888);
//獲取輸出流,用於客戶端向服務器端發送數據
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//獲取輸入流,用於接收服務器端發送來的數據
DataInputStream dis = new DataInputStream(socket.getInputStream());
//客戶端向服務器端發送數據
dos.writeUTF("我是客戶端,請求連接!");
//打印出從服務器端接收到的數據
System.out.println(dis.readUTF());
//不需要繼續使用此連接時,記得關閉哦
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶端:
public class ServerDemo {
/**
* 注意:Socket的發送與接收是需要同步進行的,即客戶端發送一條信息,服務器必需先接收這條信息,
* 而後纔可以向客戶端發送信息,否則將會有運行時出錯。
* @param args
*/
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(8888);
//服務器接收到客戶端的數據後,創建與此客戶端對話的Socket
Socket socket = ss.accept();
//用於向客戶端發送數據的輸出流
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//用於接收客戶端發來的數據的輸入流
DataInputStream dis = new DataInputStream(socket.getInputStream());
System.out.println("服務器接收到客戶端的連接請求:" + dis.readUTF());
//服務器向客戶端發送連接成功確認信息
dos.writeUTF("接受連接請求,連接成功!");
//不需要繼續使用此連接時,關閉連接
socket.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}