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();
}
}