Java TCP实现简单的即时通讯

2021-05-29 16:04

阅读:431

public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;

try {
//创建一个连接
serverSocket = new ServerSocket(9999);

while (true){
//等待连接
socket = serverSocket.accept();
//读取信息
inputStream = socket.getInputStream();

outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;

if((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
System.out.println(outputStream.toString());
}


} catch (IOException e) {
e.printStackTrace();
}finally {

if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}


}


评论


亲,登录后才可以留言!