编程知识 cdmana.com

Java - network programming (3) - TCP - transfer files and pictures to each other


* TCP

Establishing a connection , To form a channel for data transmission .

Large amount of data transfer in the connection

Connect through three handshakes , It's a reliable agreement

Connection must be established , It's a little less efficient

Socket and

ServerSocket class

TCP transmission

TCP Socket:IP Address and port , Socket

Socket and ServerSocket

Establish client and server

Once the connection is established , adopt Socket Medium IO Stream for data transmission

close socket

Again , Client and server are two independent applications .

Java--- Network programming (3)-TCP- Exchange files and pictures _ The server

TCP Transmission programming

* The basic idea ( client )

The client needs to be clear about the server ip Address and port , So you can try to establish a connection , If the connection fails , There will be anomalies .

Successful connection , It indicates that a channel has been established between the client and the server , Then through the IO Stream can transmit data , and Socket Object already provides input stream and output stream objects , adopt getInputStream(), getOutputStream() Get it .

After the communication with the server ends , close Socket.

* The basic idea ( Server side )

The server needs to be clear about which port the data to be processed enters from .

When there is client access , Be clear about which client , It can be done by accept() Get the connected client object , And communicate with the client through this object IO Stream for data transmission .

When the client access ends , Close the client .

be based on TCP Of Socket Communication process

Java--- Network programming (3)-TCP- Exchange files and pictures _ Network programming _02

TCP Transmission programming code :

* client

adopt Socket Establish the object and specify the server host and port to be connected .

      
      
Socket s = new Socket(“192.168.1.1”,9999);
OutputStream out = s.getOutputStream();
out.write(“hello”.getBytes());
s.close();
  • 1.
  • 2.
  • 3.
  • 4.

* Server side

To establish a server, you need to listen to a port

      
      
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept ();
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int num = in.read(buf);
String str = new String(buf,0,num);
System.out.println(s.getInetAddress().toString()+”:”+str);
s.close();
ss.close();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

The simplest TCP Demo example :

Client code :

      
      
package cn.hncu.tcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* client
* @author Chen Haoxiang
*
* 2016-5-10
*/
public class MyClientSocket {

public static void main(String[] args) {
try {
// Because it is demonstrated on your own machine ,IP Just fill in this machine directly 10.30.7.95 Of course. .
// This port and IP It's all server-side ( What you can change )
Socket s = new Socket("10.30.7.95", 9999);
// Shake hands with the server three times , If it fails, an exception will appear , Otherwise, return to the communication with the other party socket

OutputStream os = s.getOutputStream();
// send data
os.write(" Hello , The server !".getBytes());

// Receive feedback from the server
InputStream in = s.getInputStream();

DataInputStream din = new DataInputStream(in);

System.out.println(din.readUTF());

s.close();
din.close();

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

}

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

Server-side code :

      
      
package cn.hncu.tcp;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* Server side
* @author Chen Haoxiang
*
* 2016-5-10
*/
public class MyServerSocket {

public static void main(String[] args) {

try {
ServerSocket server = new ServerSocket(9999);
while(true){

System.out.println(" Ready to receive a data ...");
Socket s = server.accept();// Blocking method
System.out.println(" Received a data ...");

// read -- Read data from the client
InputStream in = s.getInputStream();
byte buf[] = new byte[1024];
in.read(buf);
System.out.println("read info: "+new String(buf));

// Write -- Answer client -- Write data to him
OutputStream out = s.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(" Hello ,"+s.getInetAddress().getHostAddress()+" , Your message has been received .");
dout.close();
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}


}

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.

Client run results :

      
      
Hello ,10.30.7.95 , Your message has been received .
  • 1.

Server run results :

Java--- Network programming (3)-TCP- Exchange files and pictures _ Network programming _03

* reflection

      
      
about Web For servers , When multiple clients access the server at the same time , How can the server provide services ?
  • 1.

*TCP The most common problem in transmission

Connect the client to the server , Both ends are waiting , No data transfer .

Through routine analysis :

because read Methods or readLine The method is blocking .

terms of settlement :

Custom end tag ( You must define a string that does not exist in the transfer file , Otherwise, the received data will be incomplete )

Use shutdownInput,shutdownOutput Method .

Programming practice

* Upload text files

Read a local text file , Send the data to the server , The server side stores the data . After storage , Give the client a hint .

Text file sending client

      
      
package cn.hncu.tcp.upload;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* Text file sending client
* @author Chen Haoxiang
*
* 2016-5-10
*/
public class UploadTextClient {

public static void main(String[] args) {

try {
Socket s = new Socket("", 10006);

// Ideas : Read out the data of the local file through s.getOutputStream() To obtain the out Object sent out
BufferedReader bf = new BufferedReader(new FileReader("tempfiles\\client.txt"));

OutputStream out = s.getOutputStream();// The output stream here This corresponds to the input stream on the server side
PrintWriter pw = new PrintWriter(out,true);// Not recommended BufferedWriter
//!!!!!!!!!!!!!!!!! This true Don't forget to !--- Automatically refresh
// Now let's write the network transmission file , General is to use PrintWriter

String str=null;
while((str=bf.readLine())!=null){
pw.println(str);
}

// Send an end tag to the server --- End of upload , To mark the end ,
// Otherwise, the server will call when the data is received read() or readLine() It's going to be abnormal
// Law 1:pw.println("over#[email protected]#@$");// The end keyword that exists in the file cannot appear --- Make it special
// Law 2--- It is suggested that --- from socket Internal to specify the end tag
s.shutdownOutput();
bf.close();

// Receiving feedback from the server

InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(in);
System.out.println("server The reply :"+din.readUTF());
s.close();
din.close();


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



}

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.

The server side of text file receiving

      
      
package cn.hncu.tcp.upload;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* The server side of text file receiving
* @author Chen Haoxiang
*
* 2016-5-10
*/
public class UploadTextServer {

public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(10006);

Socket s = server.accept();
System.out.println(s.getInetAddress().getHostAddress()+"... Send a message to ");

// Read the text file uploaded by the client
// Source ---socket( Byte stream )--- additional : It needs to be converted to a stream of characters , Cache stream
InputStream in = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Purpose --- Hard disk character stream FileWriter--- additional : Print stream
PrintWriter pw = new PrintWriter(new FileWriter("tempfiles\\server.txt"),true);
String line = null;
while((line=br.readLine())!=null){
// if("over#[email protected]#@$".equals(line)){// Self defined end flag
// break;
// }
pw.println(line);
}

pw.close();

// Upload successful , Give the client a prompt

OutputStream out = s.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(" File upload succeeded !");
s.close();
server.close();
dout.close();


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




}

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.

The test passed !

* Upload picture file

Client requirements : Send a picture file to the server and read the feedback information . It is required to judge whether the document exists and whether the format is jpg or gif And the document shall be less than 2M.

Server requirements : Receive the picture data sent by the client . After storage , Give back to one Upload success . Support concurrent access of multiple users .

Sending of picture files - client

      
      
package cn.hncu.tcp.upload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import javax.swing.JOptionPane;

/**
* Sending of picture files - client
* @author Chen Haoxiang
*
* 2016-5-10
*/
public class UploadPicClient {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the image path :");
String str = sc.next();

File file = new File(str);
if(!(file.exists()&& file.isFile())){
JOptionPane.showMessageDialog(null, " file does not exist !");
return ;
}

if(!(file.getName().endsWith(".jpg")||file.getName().endsWith(".gif"))){
JOptionPane.showMessageDialog(null, " The file format is not correct , The file extension must be jpg or gif!");
return ;
}
if( file.length()>=1024*1024*2){
JOptionPane.showMessageDialog(null, " File is too large. , Should not exceed 2M, Please upload again !");
return;
}

// Upload
try {
Socket s = new Socket("10.30.7.95", 10007);

BufferedInputStream bin = new BufferedInputStream(new FileInputStream(str));

OutputStream out = s.getOutputStream();

byte buf[] = new byte[1024];
int len=0;
while((len=bin.read(buf))!=-1){
out.write(buf, 0, len);
}

s.shutdownOutput();// Tell the server , File upload completed

// Read the feedback information from the server
InputStream in = s.getInputStream();
byte buf2[] = new byte[1024];
int len2 = in.read(buf2);
System.out.println(new String(buf2, 0, len2));

// Shut off flow
out.close();
bin.close();
s.close();

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

}

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.

Picture file receiving - Server side

      
      
package cn.hncu.tcp.upload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* Picture file receiving - Server side
* @author Chen Haoxiang
*
* 2016-5-10
*/
public class UploadPicServer {

public static void main(String[] args) {

try {
ServerSocket server = new ServerSocket(10007);
while(true){
Socket s = server.accept();// Blocking method
// Only responsible for handshaking with the client
new Thread(new UploadThread(s) ).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class UploadThread implements Runnable{
private Socket s;
public UploadThread(Socket s) {
this.s = s;
}

@Override
public void run() {

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"... Send pictures ");

try {
BufferedInputStream bin = new BufferedInputStream(s.getInputStream());

File dir = new File("g:\\mypic");

if(!dir.exists()){
dir.mkdir();// Folder does not exist , establish mypic Folder
}

int count=1;
// I think the suffix here , It needs to be sent through the sender
File file = new File(dir, ip+".jpg");

while(file.exists()){
file = new File(dir,ip+"("+(count++) +")"+".jpg"); // File name with number
}

FileOutputStream fout = new FileOutputStream(file);

// from socket Read data in stream , Store to local file . Equivalent to torture
byte buf[] = new byte[1024];
int len=0;
while( (len=bin.read(buf))!=-1){
fout.write(buf, 0, len);
}
// The picture is received

// Send feedback to the client
OutputStream out = s.getOutputStream();
out.write( " Upload successful ".getBytes() );

fout.close();
s.close();

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



}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.

There is a small one. bug. It is received by the server , Because I unify the suffix to jpg 了 ,gif The picture can be uploaded , It's just a static picture (jpg). You can change the suffix , Then change the picture back to the moving picture . There's another way , When uploading , Upload the suffix name , This problem can be solved through server parsing .

Because of time , I won't write it down , This is very simple .

Just sent an extra suffix in the past .

I still wrote down the solution to the suffix :

On the client side : The modified code is as follows :

      
      
// Upload
try {
Socket s = new Socket("10.30.7.95", 10007);

BufferedInputStream bin = new BufferedInputStream(new FileInputStream(str));

// Upload file suffix ########### To increase the
OutputStream out = s.getOutputStream();
String fileName = file.getName();
out.write(fileName.substring(fileName.length()-4, fileName.length()).getBytes());

byte buf[] = new byte[1024];
int len=0;
while((len=bin.read(buf))!=-1){
out.write(buf, 0, len);
}

s.shutdownOutput();// Tell the server , File upload completed

// Read the feedback information from the server
InputStream in = s.getInputStream();
byte buf2[] = new byte[1024];
int len2 = in.read(buf2);
System.out.println(new String(buf2, 0, len2));

// Shut off flow
out.close();
bin.close();
s.close();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.

Server side :

      
      
@Override
public void run() {

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"... Send pictures ");

try {


BufferedInputStream bin = new BufferedInputStream(s.getInputStream());

File dir = new File("g:\\mypic");

if(!dir.exists()){
dir.mkdir();// Folder does not exist , establish mypic Folder
}


// Read the suffix of the uploaded picture !#########
char cbuf[] = new char[4];
InputStreamReader insr = new InputStreamReader(bin);
insr.read(cbuf);
String str = new String(cbuf);

int count=1;
// I think the suffix here , It needs to be sent through the sender
File file = new File(dir, ip+str);

while(file.exists()){
file = new File(dir,ip+"("+(count++) +")"+str); // File name with number
}

FileOutputStream fout = new FileOutputStream(file);

// from socket Read data in stream , Store to local file . Equivalent to torture
byte buf[] = new byte[1024];
int len=0;
//######### There must be this sentence
bin.read(buf, 0, 8);
while( (len=bin.read(buf))!=-1){
fout.write(buf, 0, len);
}
// The picture is received

// Send feedback to the client
OutputStream out = s.getOutputStream();
out.write( " Upload successful ".getBytes() );

fout.close();
s.close();

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



}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.

Okay , It's basically like this , If you want to be better , A graphical interface will look good . Do it yourself ~~



版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/134/202205141204236837.html

Scroll to Top