public class TcpClient {
public static void main(String[] args) {
Socket socket =null;
OutputStream os =null;
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port=9999;
socket = new Socket(serverIP,port);
os = socket.getOutputStream();
os.write("我想你了啊".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket =null;
InputStream is =null;
ByteArrayOutputStream baos =null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while((len=is.read(bytes))!=-1){
baos.write(bytes,0,len);
}
System.out.println(baos.toString());
} catch (Exception 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(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
这块需要注意的是 **socket.shutdownOutput()**在客户端或者服务端通过socket.shutdownOutput()都是单向关闭的,即关闭客户端的输出流并不会关闭服务端的输出流,所以是一种单方向的关闭流; 通过socket.shutdownOutput()关闭输出流,但socket仍然是连接状态,连接并未关闭 如果直接关闭输入或者输出流,即:in.close()或者out.close(),会直接关闭socket
public class TcpServer2 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File("jieshouwenjian.PNG"));
byte[] bytes = new byte[1024];
int len=0;
while((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
OutputStream outputStream1 = socket.getOutputStream();
outputStream1.write("我知道啊,我也很想你".getBytes());
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
public class TcpClient2 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8999);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("D:\\IDEA\\网络编程\\src\\捕获.PNG"));
byte[] bytes = new byte[1024];
int len=0;
while((len=fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes2 = new byte[1024];
int len2=0;
while((len2=inputStream.read(bytes2))!=-1){
byteArrayOutputStream.write(bytes2,0,len2);
}
System.out.println(byteArrayOutputStream.toString());
inputStream.close();
byteArrayOutputStream.close();
fis.close();
os.close();
socket.close();
}
}