Tcp学习Serve
作者:互联网
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server{
public static void main(String[] args) {
ByteArrayOutputStream baos = null;
InputStream is = null;
Socket acc = null;
ServerSocket serverSocket = null;
//1 建立连接
try {
//
serverSocket = new ServerSocket(8888);
//等待客户端连接
acc = serverSocket.accept();
//读取客户端连接
is = acc.getInputStream();
/****
*
*
* 建立缓冲区
*/
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (acc != null) {
try {
acc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
标签:java,Serve,Tcp,学习,printStackTrace,IOException,import,baos,null 来源: https://www.cnblogs.com/gethub/p/16103608.html