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