ceiicomnnectionservce壁咚是什么意思

Sockets programming in Java: A tutorial | JavaWorld
Most read:
Insider email
Use commas to separate multiple email addresses
Sockets programming in Java: A tutorial
More like this
Write your own client/server applications seamlessly in Java
By Qusay H. Mahmoud
This classic JavaWorld tutorial presents an introduction to sockets programming over TCP/IP networks and demonstrates how to write client/server applications in Java.
A bit of history
The Unix input/output (I/O) system follows a paradigm usually referred to as Open-Read-Write-Close. Before a user process can perform I/O operations, it calls Open to specify and obtain permissions for the file or device to be used. Once an object has been opened, the user process makes one or more calls to Read or Write data. Read reads data from the object and transfers it to the user process, while Write transfers data from the user process to the object. After all transfer operations are complete, the user process calls Close to inform the operating system that it has finished using that object.
When facilities for InterProcess Communication (IPC) and networking were added to Unix, the idea was to make the interface to IPC similar to that of file I/O. In Unix, a process has a set of I/O descriptors that one reads from and writes to. These descriptors may refer to files, devices, or communication channels (sockets). The lifetime of a descriptor is made up of three phases: creation (open socket), reading and writing (receive and send to socket), and destruction (close socket).
The IPC interface in BSD-like versions of Unix is implemented as a layer over the network TCP and UDP protocols. Message destinations are specified each socket address is a communication identifier that consists of a port number and an Internet address.
The IPC operations are based on socket pairs, one belonging to a communication process. IPC is done by exchanging some data through transmitting that data in a message between a socket in one process and another socket in another process. When messages are sent, the messages are queued at the sending socket until the underlying network protocol has transmitted them. When they arrive, the messages are queued at the receiving socket until the receiving process makes the necessary calls to receive them.
TCP/IP and UDP/IP communications
There are two communication protocols that one can use for socket programming: datagram communication and stream communication.
Datagram communication:
The datagram communication protocol, known as UDP (user datagram protocol), is a connectionless protocol, meaning that each time you send datagrams, you also need to send the local socket descriptor and the receiving socket's address. As you can tell, additional data must be sent each time a communication is made.
Stream communication:
The stream communication protocol is known as TCP (transfer control protocol). Unlike UDP, TCP is a connection-oriented protocol. In order to do communication over the TCP protocol, a connection must first be established between the pair of sockets. While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions.
Now, you might ask what protocol you should use -- UDP or TCP? This depends on the client/server application you are writing. The following discussion shows the differences between the UDP and TCP this might help you decide which protocol you should use.
In UDP, as you have read above, every time you send a datagram, you have to send the local descriptor and the socket address of the receiving socket along with it. Since TCP is a connection-oriented protocol, on the other hand, a connection must be established before communications between the pair of sockets start. So there is a connection setup time in TCP.
In UDP, there is a size limit of 64 kilobytes on datagrams you can send to a specified location, while in TCP there is no limit. Once a connection is established, the pair of sockets behaves like streams: All available data are read immediately in the same order in which they are received.
UDP is an unreliable protocol -- there is no guarantee that the datagrams you have sent will be received in the same order by the receiving socket. On the other hand, TCP is it is guaranteed that the packets you send will be received in the order in which they were sent.
In short, TCP is useful for implementing network services -- such as remote login (rlogin, telnet) and file transfer (FTP) -- which require data of indefinite length to be transferred. UDP is less complex and incurs fewer overheads. It is often used in implementing client/server applications in distributed systems built over local area networks.
Programming sockets in Java
In this section we will answer the most frequently asked questions about programming sockets in Java. Then we will show some examples of how to write client and server applications.
Note: In this tutorial we will show how to program sockets in Java using the TCP/IP protocol only since it is more widely used than UDP/IP. Also: All the classes related to sockets are in the java.net package, so make sure to import that package when you program sockets.
How do I open a socket?
If you are programming a client, then you would open a socket like this:
Socket MyC
MyClient = new Socket("Machine name", PortNumber);
Where Machine name is the machine you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root). These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!
In the example above, we didn't make use of exception handling, however, it is a good idea to handle exceptions. (From now on, all our code will handle exceptions!) The above can be written as:
Socket MyC
MyClient = new Socket("Machine name", PortNumber);
catch (IOException e) {
System.out.println(e);
If you are programming a server, then this is how you open a socket:
ServerSocket MyS
MyServerice = new ServerSocket(PortNumber);
catch (IOException e) {
System.out.println(e);
When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket =
serviceSocket = MyService.accept();
catch (IOException e) {
System.out.println(e);
How do I create an input stream?
On the client side, you can use the DataInputStream class to create an input stream to receive response from the server:
DataInputS
input = new DataInputStream(MyClient.getInputStream());
catch (IOException e) {
System.out.println(e);
The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. Use whichever function you think suits your needs depending on the type of data that you receive from the server.
On the server side, you can use DataInputStream to receive input from the client:
DataInputS
input = new DataInputStream(serviceSocket.getInputStream());
catch (IOException e) {
System.out.println(e);
How do I create an output stream?
On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io:
output = new PrintStream(MyClient.getOutputStream());
catch (IOException e) {
System.out.println(e);
The class PrintStream has methods for displaying textual representation of Java primitive data types. Its Write and println methods are important here. Also, you may want to use the DataOutputStream:
DataOutputS
output = new DataOutputStream(MyClient.getOutputStream());
catch (IOException e) {
System.out.println(e);
The class DataOutputStream allows you to write Java
many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.
On the server side, you can use the class PrintStream to send information to the client.
output = new PrintStream(serviceSocket.getOutputStream());
catch (IOException e) {
System.out.println(e);
Note: You can use the class DataOutputStream as mentioned above.
How do I close sockets?
You should always close the output and input stream before you close the socket.
On the client side:
output.close();
input.close();
MyClient.close();
catch (IOException e) {
System.out.println(e);
On the server side:
output.close();
input.close();
serviceSocket.close();
MyService.close();
catch (IOException e) {
System.out.println(e);
In this section we will write two applications: a simple SMTP (simple mail transfer protocol) client, and a simple echo server.
1. SMTP client
Let's write an SMTP (simple mail transfer protocol) client -- one so simple that we have all the data encapsulated within the program. You may change the code around to suit your needs. An interesting modification would be to change it so that you accept the data from the command-line argument and also get the input (the body of the message) from standard input. Try to modify it so that it behaves the same as the mail program that comes with Unix.
import java.io.*;
import java.net.*;
public class smtpClient {
public static void main(String[] args) {
// declaration section:
// smtpClient: our client socket
// os: output stream
// is: input stream
Socket smtpSocket =
DataOutputStream os =
DataInputStream is =
// Initialization section:
// Try to open a socket on port 25
// Try to open input and output streams
smtpSocket = new Socket("hostname", 25);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 25
if (smtpSocket != null && os != null && is != null) {
// The capital string before each colon has a special meaning to SMTP
// you may want to read the SMTP specification, RFC1822/3
os.writeBytes("HELO\n");
os.writeBytes("MAIL From: k3is@fundy.csd.unbsj.ca\n");
os.writeBytes("RCPT To: k3is@fundy.csd.unbsj.ca\n");
os.writeBytes("DATA\n");
os.writeBytes("From: k3is@fundy.csd.unbsj.ca\n");
os.writeBytes("Subject: testing\n");
os.writeBytes("Hi there\n"); // message body
os.writeBytes("\n.\n");
os.writeBytes("QUIT");
// keep on reading from/to the socket till we receive the "Ok" from SMTP,
// once we received that then we want to break.
String responseL
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException:
When programming a client, you must follow these four steps:
Open a socket.Open an input and output stream to the socket.Read from and write to the socket according to the server's protocol.Clean up.
These steps are pretty much the same for all clients. The only step that varies is step three, since it depends on the server you are talking to.
2. Echo server
Now let's write a server. This server is very similar to the echo server running on port 7. Basically, the echo server receives text from the client and then sends that exact text back to the client. This is just about the simplest server you can write. Note that this server handles only one client. Try to modify it to handle multiple clients using threads.
White Paper
Popular on JavaWorld
Would you believe that Java is poised to dominate the next explosion of the Internet? Built for...
Newsletters Stay up to date on the latest tutorials and Java community news posted on JavaWorld Get our Enterprise Java newsletter
Find out how Eclipse, NetBeans, JDeveloper, and IntelliJ IDEA stack up today in capabilities and ease...
If you're new to Java then you've come to the right place: Get started with the foundations of the Java...
Popular Resources
White Paper
White Paper
White Paper
White Paper
White Paper
Featured Stories
DataTorrent is releasing its real-time data processing engine for Hadoop and beyond as the open source...
LinkedIn's open source, home-brew OLAP project is a new way for Hadoop users (and others) to query both...
Sure, a NoSQL or JSON data warehouse sounds faddish, but SonarW is a better solution for many.
The move could be Google's way of attracting more external committers to the JavaScript rival.Apache Maven Shade Plugin – Resource Transformers
Resource Transformers
Version: 2.4
Resource Transformers
Aggregating classes/resources from several artifacts into one uber JAR is straight forward as long as there is no overlap. Otherwise, some kind of logic to merge resources from several JARs is required. This is where resource transformers kick in.
Transformers in org.apache.maven.plugins.shade.resource
Prevents license duplication
Prepares merged NOTICE
Adds content to a resource
Aggregates Plexus components.xml
Prevents inclusion of matching resources
Adds files from the project
Sets entries in the MANIFEST
Aggregates Mavens plugin.xml
Merges META-INF/services resources
Adds XML content to an XML resource
Merging Plexus Component Descriptors with the
JARs for components targeting the Plexus IoC container contain a META-INF/plexus/components.xml entry that declares the component and its requirements. If the uber JAR aggregates multiple Plexus components, a ComponentsXmlResourceTransformer needs to be used to merge the XML descriptors:
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.ponentsXmlResourceTransformer&/&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Since plugin version 1.3, this resource transformer will also update the descriptor to account for relocation of component interfaces/implementations (if any).
Relocate classes of the Maven Plugin Descriptor with the
annotations have been introduced. Now references to classes are no longer classnames as String, but the actual Class reference. When you wanted to relocate classes, you had to maintain the META-INF/maven/plugin.xml by hand, but now this can be done with the PluginXmlResourceTransformer
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.PluginXmlResourceTransformer&/&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Concatenating Service Entries with the
JAR files providing implementations of some interfaces often ship with a META-INF/services/ directory that maps interfaces to their implementation classes for lookup by the service locator. To merge multiple implementations of the same interface into one service entry, the ServicesResourceTransformer can be used:
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.ServicesResourceTransformer&/&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Merging Content of Specific Files with
and XmlAppendingTransformer
Some jars contain additional resources (such as properties files) that have the same file name. To avoid overwriting, you can opt to merge them by appending their content into one file. One good example for this is when aggregating both the spring-context and plexus-spring jars. Both of them have the META-INF/spring.handlers file which is used by Spring to handle XML schema namespaces. You can merge the contents of all the files with that specific name using the AppendingTransformer as shown below:
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.AppendingTransformer&&
&resource&META-INF/spring.handlers&/resource&
&/transformer&
&transformer implementation=&org.apache.maven.plugins.shade.resource.AppendingTransformer&&
&resource&META-INF/spring.schemas&/resource&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
For XML files, you can use the
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.XmlAppendingTransformer&&
&resource&META-INF/magic.xml&/resource&
&!-- Add this to enable loading of DTDs
&ignoreDtd&false&/ignoreDtd&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Since plugin version 1.3.1, the XmlAppendingTransformer will by default not load DTDs, thereby avoiding network access. The potential downside of this mode is that external entities cannot be resolved which could fail the transformation, e.g. when using the Crimson XML parser as used in some JRE 1.4. If the transformed resource uses external entities, DTD resolution can either be turned back on or a plugin dependency on xerces:xercesImpl:2.9.1 is added to the POM.
Excluding Resources with the
The DontIncludeResourceTransformer allows resources to be excluded when their name ends in a given value.
For example, the following sample excludes all resources ending in .txt.
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer&&
&resource&.txt&/resource&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Since maven-shade-plugin-3.0 it is also possible to give a list of resources which should not be included, like:
&transformer implementation=&org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer&&
&resources&
&resource&.txt&/resource&
&resource&READ.me&/resource&
&/resources&
&/transformer&
Adding New Resources with the
The IncludeResourceTransformer allows project files to be included in the package under a given name.
For example, the following sample includes README.txt in the package as README in the META-INF directory.
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.IncludeResourceTransformer&&
&resource&META-INF/README&/resource&
&file&README.txt&/file&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Setting Manifest Entries with the
The ManifestResourceTransformer allows existing entries in the MANIFEST to be replaced and new entries added.
For example, the following sample sets
the Main-Class entry to the value of the app.main.class property,
the X-Compile-Source-JDK entry to the value of the <pile.source property and
the X-Compile-Target-JDK entry to the value of the <pile.target property.
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.ManifestResourceTransformer&&
&manifestEntries&
&Main-Class&${app.main.class}&/Main-Class&
&X-Compile-Source-JDK&${pile.source}&/X-Compile-Source-JDK&
&X-Compile-Target-JDK&${pile.target}&/X-Compile-Target-JDK&
&/manifestEntries&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Preventing License Duplication with the
Some open source producers (including the ) include a copy of their license in the META-INF directory. These are conventionally named either LICENSE or LICENSE.txt. When merging these dependencies, adding these resources may cause confusion. The ApacheLicenseResourceTransformer ensures that duplicate licenses (named according to this convention) are not merged.
For example, the following prevents the license from a commons-collections dependency being merged in
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer&&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Aggregating Notices with the
Some licenses (including the ) require that notices are preserved by downstream distributors. ApacheNoticeResourceTransformer automates the assembly of an appropriate NOTICE.
For example, to simply merge in dependent notices:
&groupId&org.apache.maven.plugins&/groupId&
&artifactId&maven-shade-plugin&/artifactId&
&version&2.4&/version&
&executions&
&execution&
&phase&package&/phase&
&goal&shade&/goal&
&configuration&
&transformers&
&transformer implementation=&org.apache.maven.plugins.shade.resource.ApacheNoticeResourceTransformer&&
&addHeader&false&/addHeader&
&/transformer&
&/transformers&
&/configuration&
&/execution&
&/executions&
&/plugins&
&/project&
Copyright &
All rights reserved.

我要回帖

更多关于 servce 122.c 的文章

 

随机推荐