服务器:
public class SocketDemo {
public static final int PORT = 6666;
public synchronized void start(){
System.out.println("服务器启动... ...");
try (ServerSocket serverSocket = new ServerSocket(PORT)){
while (true) {
Socket socket = serverSocket.accept();
ExecutorService executorService = Executors.newFixedThreadPool(10);
System.out.println("服务器已连接" + socket.getInetAddress());
executorService.execute(new HandleReadRunnable(socket));
executorService.execute(new HandleWriteRunnable(socket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SocketDemo().start();
}
}
客户端:
public class ClientDemo {
public void send(String in,int port) throws IOException {
Socket socket = new Socket(in,port);
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new HandleReadRunnable(socket));
executorService.execute(new HandleWriteRunnable(socket));
}
public static void main(String[] args) throws IOException {
new ClientDemo().send("192.168.1.xxx",6666);//输入自己的ip地址
}
}
写入的方法:
public class HandleWriteRunnable implements Runnable {
private Socket socket;
public HandleWriteRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
while (true){
System.out.println(Thread.currentThread().getName()+"-说:");
String s = scanner.next();
outputStream.writeUTF(s);
outputStream.flush();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
输出的方法:
public class HandleReadRunnable implements Runnable{
private Socket socket;
public HandleReadRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
while (true){
String s = in.readUTF();
System.out.println(s);
}
}catch (IOException e) {
e.printStackTrace();
}
}
}