今天学习了一下java如何实现socket通信,感觉难点反而是在io上,因为java对socket封装已经很完善了。

  今天代码花了整个晚上调试,主要原因是io的flush问题和命令行下如何运行具有package的类,不过最后问题基本都解决了,把代码贴出来供大家参考

server

public class TcpServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(9091);
try {
Socket client = server.accept();
try {
BufferedReader input =
new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean flag = true;
int count = 1; while (flag) {
System.out.println(客户端要开始发骚了,这是第 + count + 次!);
count++; String line = input.readLine();
System.out.println(客户端说: + line); if (line.equals(exit)) {
flag = false;
System.out.println(客户端不想玩了!);
} else {
System.out.println(客户端说: + line);
} }
} finally {
client.close();
} } finally {
server.close();
}
}
}

client

public class TcpClient {
public static void main(String[] args) throws Exception {
Socket client = new Socket(127.0.0.1, 9091);
try {
PrintWriter output =
new PrintWriter(client.getOutputStream(), true);
Scanner cin = new Scanner(System.in);
String words; while (cin.hasNext()) {
words = cin.nextLine(); output.println(words); System.out.println(写出了数据: + words);
} cin.close();
} finally {
client.close();
}
}
}

最新文章

  1. bzoj 3211: 花神游历各国
  2. jquery实现动态添加html代码
  3. ubuntu静态IP配置
  4. jQuery 删除元素
  5. 在 Windows 下远程桌面连接 Linux - XManager 篇
  6. Java static块
  7. oracle 转让日期格式字符串
  8. Linux系列教程(二)——Linux系统安装(手把手学安装centos6.8)
  9. NameNode和SecondaryNameNode工作原理剖析
  10. Elasticsearch大规模时序索引如何治理和规划
  11. jsp请求java返回pdf、excel与word
  12. 深入浅出Git教程【转载】转载
  13. webpack之牛刀小试 打包并压缩html、js
  14. fastcgi协议分析与实例
  15. c3 新特性
  16. Linux系统性能优化
  17. js实例属性和原型属性
  18. 双11抢券,写一个自动打开页面的html,仅仅是设定时间打开抢券的页面
  19. request使用代理
  20. 撩课-Java每天5道面试题第12天

热门文章

  1. 123apps-免费网络应用
  2. squid如何屏蔽User-Agent为空的请求
  3. 高级vim 配置
  4. 剑指Offer的学习笔记(C#篇)-- 和为S的连续正数序列
  5. 在Drupal7中创建web接口
  6. InstallShield Limited Edition for Visual Studio 2013 图文教程打包安装包
  7. KVM修改虚机网卡模式:由NAT模式改为Bridge模式
  8. js数据结构与算法--递归
  9. vue购物车的实现
  10. 19.VUE学习之- v-for与computed结合功能 筛选实例讲解