利用socket套间字进行服务器和客户端之间的简单通信
服务器端
package com.xiaowu.test9_14;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器端
* @author magic_xiaowu
*
*/
public class MyServer {
public static void main(String[] args) {
ServerSocket ss= null;
try {
ss = new ServerSocket(8888);
Socket socket = ss.accept();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeUTF("客户端,你好啊~!");
System.out.println(dis.readUTF());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
客户端
package com.xiaowu.test9_14;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
/**
* 客户端
* @author magic_xiaowu
*
*/
public class MyClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 8888);
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("你好!服务器");
System.out.println(dis.readUTF());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}