The Java socket is based on the TCP/IP protocol

Source: Internet
Author: User

Java socket based TCP/IP protocol application

Multi-Threaded Server principle:

1, the server side creates the ServerSocket and binds the port number to listen, loops calls the Serversoket's accept () method, waits for the client's connection request

2. Client creates a socket-bound server-side IP address and server-listening port number and requests and server-side connections

3. After the server receives the client's request, create a socket to establish a leased line connection with the client.

4. Connect the two sockets dialog on a separate thread

5. Server side continues to wait for new connections

Socket.shutdownoutput (); and socket.shutdowninput () note the distinction between

Note: Most of the time when the client transmits data to the server, it encapsulates the data as an object rather than the string used in this article.

Socket socket = new socket ("localhost", 8888);
OutputStream os =socket.getoutputstream ();
Using the ObjectOutputStream object to serialize the stream, passing the object
Objectoutputstreamobjectoutputstream =new objectoutputstream (OS);
User user = New User ("Most handsome", "123");//encapsulate data as a user object
Serialization of
Objectoutputstream.writeobject (user);
Socket.shutdownoutput ();
BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
String info = br.readline ();
while (info! = null) {
System. out. println ("Here is the client, the server came up with a message:" +info);
Info =br.readline ();

Passing files

Objectinputstreamclientinputstream = null;
First generate a temporary file after download
String filenaemtemp= "Temp.txt";
String Downloadpath =configmanager.getinstance (0.getString (CONSTANTS.CLIENT_DOWNLOAD_PA
try{
Clientinputstream = new ObjectInputStream (Clientsocket.getinputstream ());
File Filetemp = new file (Downloadpath + "/" +filenaemtemp);
if (filetemp.exists ()) {
Filetemp.delete ();
}
Filetemp.createnewfile ();
Bufferedoutputstream Bufferedoutputstream = Newbufferedoutputstream (new FileOutputStream (fileTemp));
Accept the server's files
byte []buf = new byte[1024];
int Len;
while ((len= clientinputstream.read (BUF))! =-1) {
Bufferedoutputstream.write (Buf,0,len);
Bufferedoutputstream.flush ();

Client:

Import Java.net.Socket;

/**
*
Description: Client
* Created by Jim Calark on 2017/3/17.
*/
public class Client {
public static void Main (String[]args) {


try {
Create a client socket, specify the server IP address and port number
Socket socket = new socket ("localhost", 65533);

Get socket output stream
OutputStream os =socket.getoutputstream ();

/convert byte output to print stream
PrintWriter pw = new PrintWriter (OS);

Output to server side
Pw.write ("Hello, I am the client");

Punch Flow
Pw.flush ();

Pw.close ()//The output stream cannot be closed here, which will cause the socket to close; Close Socke

Automatically shuts down the output stream under the socket.

Off the output stream is off the wrong side, shut down the input stream and tell the server to send the message.

Without shutting down the output stream, the card will always read the data in the thread there

Socket.shutdownoutput ();


Get the socket input stream and read server-side response information
InputStream is =socket.getinputstream ();

Convert byte stream to character stream to improve reading efficiency
InputStreamReader ISR = new InputStreamReader (IS);

Set buffer for character stream
BufferedReader br = new BufferedReader (ISR);
String data = null;

Looping through data
while ((data = Br.readline ()) = null) {
System. out. println (data);

}
Close Resource
Is.close ();
Isr.close ();
Br.close ();
Pw.close ();
Socket.close ();
} catch (IOException e) {
E.printstacktrace ();
}


}
}

Communication Thread Class
Import java.io.*;
Import Java.net.Socket;


/**
* @
Description: Thread service class
* Created by Jim Calark on 2017/3/17.
*/


public class Serverthread extends thread{
/** socket related to this thread */
Socket socket = NULL;
constructor with socket as parameter
Public serverthread (socket socket) {
This.socket = socket;
}
The action that the thread performs to respond to the customer's request
public void Run () {
InputStream is = null;
OutputStream OS = null;
BufferedReader br = null;
InputStreamReader ISR = null;
PrintWriter pw = null;


try {

Gets the byte input stream of the client request in the socket
is = Socket.getinputstream ();
Stream byte input to character input
ISR = new InputStreamReader (IS);
Create buffers to improve data read efficiency
br = new BufferedReader (ISR);
String data = null;
Iterate through the data, reading one line at a time
while ((data = Br.readline ()) = null) {
Print data
System. out. println ("Message from the client" +data);
}

Socket.shutdowninput ();//Close input stream

Get output Stream Response client request
OS = Socket.getoutputstream ();
PW = new PrintWriter (OS);
Pw.write ("Welcome to the server side!") ");
Pw.flush ();//Call Flush () method to buffer output


} catch (IOException e) {
E.printstacktrace ();
}
finally {
Close Resource
try{
if (is!=null) {
Is.close ();
}
if (ISR! = null) {
Isr.close ();
}
if (br! = null) {
Br. Close ();
}
if (OS! = null) {
Os.close ();
}
if (PW = null) {
Pw.close ();

}
if (socket! = NULL) {
Socket.close ();
}

}catch (IOException e) {
E.printstacktrace ();
}



}


}

Server-side
Import java.io.IOException;
Import Java.net.ServerSocket;
Import Java.net.Socket;

/**
* @
Description: Server-side class
* Created by Jim Calark on 2017/3/17.
*/
public class Server {
public static void Main (string[] args) {

try {
Create a server-side ServerSocket class that binds the port number to be monitored
ServerSocket serversocket = new ServerSocket (65533);
Socket socket = NULL;
Log the number of client connections
int count = 0;
System. out. println ("********** server is about to start, waiting for client Connection ********************");
Loop monitoring waits for a client's connection
while (true) {
Call ServerSocket's accept () to start the method of listening, waiting for the client connection, once the connection creates a server-side socket
Socket = Serversocket.accept ();
Create a new thread for a new connection
Serverthread serverthread = new Serverthread (socket);
Sets the priority of the thread, in the range of [1,10], which defaults to 5. Not setting a priority may result in a running speed level
Very slow, can reduce the priority level
Serverthread.setpriority (4);
Start thread
Serverthread.start ();
count++;
System. out. println ("Current Total" +count + "Client Connection");
}
} catch (IOException e) {
E.printstacktrace ();
}

}
}

The Java socket is based on the TCP/IP protocol

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.