标签:
服务端代码: public class TalkServer { public static void main(String args[]){ try { //创建服务器,开放7777端口 ServerSocket server = new ServerSocket(7777); while(true){ Socket socket = server.accept(); System.out.println("客户端与服务端已建立连接"); //获取客户端消息 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = br.readLine(); System.out.println("客户端消息:"+ message); server.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客户端代码:
public class TalkClient { public static void main(String args[]){ try { Socket socket = new Socket("127.0.0.1",7777); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); Scanner scanner = new Scanner(System.in); while(true){ System.out.println("请输入发送消息内容:"); bw.write(scanner.nextLine()); bw.flush(); socket.close(); scanner.close(); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
1、如果没有客户端服务,直接通过浏览器发送请求,即输入http://127.0.0.1:7777或localhost:7777,服务端运行结果:
客户端与服务端已建立连接
客户端消息:GET / HTTP/1.1
2、socket创建客户端发送请求,通过键盘输入发送请求
客户端运行结果:
请输入发送消息内容:
hello
服务端运行结果:
客户端与服务端已建立连接
客户端消息:hello
标签:
原文地址:http://www.cnblogs.com/worms/p/5726949.html