2019独角兽企业重金招聘Python工程师标准>>>
1、Server端
package com.hhdys.serviceimpl;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;/*** Created by hhdys on 16/7/22.*/
public class Server {private static List<Socket> clients = new ArrayList<Socket>();public static void main(String[] args) {try {System.out.println("begin==================");ServerSocket serverSocket = new ServerSocket(8088);while (true) {System.out.println("请输入你要进行的操作!");Scanner scanner = new Scanner(System.in);while (scanner.hasNextInt()) {int i = scanner.nextInt();if (i == 1) {read(serverSocket);} else {write();}}scanner.close();}} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}System.out.println("end==============");}private static void read(ServerSocket serverSocket) throws Exception {System.out.println("开始监听===" + clients.size());final Socket socket = serverSocket.accept();clients.add(socket);new Thread(new Runnable() {public void run() {try {InputStream in = socket.getInputStream();Scanner scanner = new Scanner(in);while (true) {while (scanner.hasNextLine()) {System.out.println(scanner.nextLine());}TimeUnit.SECONDS.sleep(1);}} catch (IOException e) {e.printStackTrace();}catch (Exception e){e.printStackTrace();}}}).start();}public static void write() throws Exception {System.out.println("发送server消息====");Socket socket = clients.get(0);OutputStream out = socket.getOutputStream();BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));writer.write("我是服务端哈哈哈哈!你好");writer.newLine();writer.flush();// writer.close();// out.close();}}
2、Client端
package com.hhdys.serviceimpl;import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;/*** Created by hhdys on 16/7/22.*/
public class Client {private static Socket socket=null;public static void main(String[] args){System.out.println("begin==========");try {socket=new Socket("127.0.0.1",8088);socket.setKeepAlive(true);System.out.println("client======");OutputStream out = socket.getOutputStream();InputStream in = socket.getInputStream();final BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));final Scanner scanner1 = new Scanner(in);Scanner scanner=new Scanner(System.in);while(true){System.out.println("输入你的操作!");if(scanner.hasNextInt()){int i=scanner.nextInt();if(i==1){new Thread(new Runnable() {public void run() {try {writer.write("我是客户端哈哈哈哈!你好");writer.newLine();writer.flush();} catch (IOException e) {e.printStackTrace();}}}).start();}else{while (scanner1.hasNextLine()) {System.out.println(scanner1.nextLine());}scanner1.close();}}TimeUnit.SECONDS.sleep(1);}} catch (IOException e) {e.printStackTrace();}catch (Exception e){e.printStackTrace();}System.out.println("end===========");}
}