TCP实现聊天

IO流关闭是简写的,正常写要判断是否为null

客户端:(最好捕获异常)

1.连接服务器Socket

2.发送消息

package net.TCPChat;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket; // 客户端
public class TcpClientDemo01 {
public static void main(String[] args) throws IOException {
//1.要知道服务器的地址
InetAddress serverIp=InetAddress.getByName("127.0.0.1");
//2.端口号
int port = 9999;
//3.创建socket连接
Socket socket = new Socket(serverIp, port);
//4.发送消息 IO流
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好,欢迎学习".getBytes());
outputStream.close();
socket.close();
}
}

服务器:(最好捕获异常)

1.建立服务的端口:ServerSocket

2.等待用户的连接:accept

3.接收用户的消息

public static void main(String[] args) throws IOException {
//1.我要有一个地址
ServerSocket serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
Socket accept = serverSocket.accept();
//3.读取客户端的消息
InputStream inputStream = accept.getInputStream();
//管道流
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
baos.close();
inputStream.close();
accept.close();
serverSocket.close();
}

最新文章

  1. 特征检测之Haar
  2. Linux之head、tail、grep、cut等命令详解
  3. Windows Azure HandBook (3) 浅谈Azure安全性
  4. globals()
  5. Oracle corrupt block(坏块) 详解
  6. Real-Rime Rendering (2) - 变换和矩阵(Translation and Matrics)
  7. rsyslog同步history日志(转载)
  8. .net 和java JSON 模板
  9. XNA 4.0 环境搭建和 Hello World,Windows Phone 游戏开发
  10. apache bench(ab)压力测试模拟POSt请求
  11. EditText光标居上
  12. 如何用Math.max.apply()获取数组最大/小值
  13. p12文件和mobileprovision文件
  14. hive入门学习线路指导
  15. windows server 2008 R2安装图片浏览器/照片查看器方法
  16. Java代理和动态代理机制分析和应用
  17. html5-css边框img
  18. String [] args是干什么的
  19. CodeForces 651 C Watchmen
  20. maven 统一管理依赖的版本号

热门文章

  1. 39、wget、curl
  2. 29、html介绍
  3. docker下创建redis cluster集群
  4. powerpoint2013去掉图片背景,转存png
  5. java 的 IO简单理解
  6. 4shell中的特殊变量
  7. buu SimpleRev
  8. 测试基础(三) Jmeter安装
  9. CF1539B Love Song[题解]
  10. PYTHON UNRAR