Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8534
  • 博文数量: 4
  • 博客积分: 181
  • 博客等级: 入伍新兵
  • 技术积分: 55
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-21 20:07
文章分类
文章存档

2012年(4)

我的朋友
最近访客

分类: Java

2012-09-26 17:27:43

     写一个Server类,这个类用来监听10000端口,并从这个端口接收消息然后输出,当收到“bye”时退出。

  package com.googlecode.garbagecan.test.socket.sample1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(10000); Socket socket = server.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); while (true) { String msg = in.readLine(); System.out.println(msg); out.println("Server received " + msg); out.flush(); if (msg.equals("bye")) { break; } } socket.close(); } }

  然后是一个Client类,这个类连接上面启动的Server类,然后接收任何用户输入,当遇到回车时发送字符串到Server上,当输入“bye”是退出。

  package com.googlecode.garbagecan.test.socket.sample1; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class MyClient { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 10000); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = reader.readLine(); out.println(msg); out.flush(); if (msg.equals("bye")) { break; } System.out.println(in.readLine()); } socket.close(); } }

  最后,首先运行MyServer类,然后MyClient类,然后在MyClient的控制台输入任意字符,可以看到当输入bye是server和client都会退出。

阅读(357) | 评论(0) | 转发(0) |
0

上一篇:锁优化和线程安全

下一篇:没有了

给主人留下些什么吧!~~