Java,socket,nio Essay Records

Source: Internet
Author: User

The answer is very good. Sockets and Socketchannel are two sets of APIs, for network TCP communication is not concerned about what API you use to achieve communication. So the answer is yes. Socketchannel can be set to non-blocking, so in some cases the performance is better and the thread will not be suspended. Socketchannel can also register selector and events of interest. Selector Multiplexer There is not much to introduce.

The flow of data in the communication process is described here. First, when the data is received by the network card, it will be saved to the kernel, the computer for unpacking parsing, look at the source port number, the packet will be saved to the corresponding link of the TCP receive buffer (in some places to become the socket buffer). When this buffer is full, the action that occurs is to notify the window in the peer TCP protocol to close. This is the implementation of the sliding window. Ensures that TCP is reliably transmitted. Because the other party is not allowed to emit more than the advertised window size data. This is the traffic control for TCP. (The hedgehog himself understands that if there is not accurate also hope to be raised)

Shrimp Noodle Talk about the simple implementation logic on the server side of the chat program. We're going to have a private conversation. When two clients establish a connection to the server, the server stores all client information that establishes the connection: Name,socket or Socketchannel that includes the client (which is returned when the connection is established). Where a client sends information to the B client "b,hello! ”。 When the server receives the message, it intercepts the string "B" and gets out the corresponding socket (NiO is Socketchannel), where it writes the read content. Complete your private chat. Shrimp noodles posted on the service side of the program: (The format is not live to see it, a few days ready to use Netty to achieve this function)

Package com.server;

Import java.io.IOException;
Import Java.io.OutputStream;
Import java.net.InetSocketAddress;
Import Java.net.Socket;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.SelectionKey;
Import Java.nio.channels.Selector;
Import Java.nio.channels.ServerSocketChannel;
Import Java.nio.channels.SocketChannel;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Set;

Import Com.server.vo.UserInfo;

public class Nioserver implements Runnable {

private static hashmap<string,userinfo> users=new hashmap<string,userinfo> ();

Private Socket client;

Private Selector Selector;

Private Serversocketchannel Serverchannel;

Private volatile Boolean stop;

Private UserInfo UserInfo;

/**
* Initializing multiplexer, binding listening port
*/
public nioserver (int port) {
try {
selector = Selector.open ();
Serverchannel = Serversocketchannel.open ();
Serverchannel.configureblocking (FALSE);
Serverchannel.bind (New inetsocketaddress (port), 1024);
Serverchannel.register (selector, selectionkey.op_accept);
} catch (Exception e) {
E.printstacktrace ();
}
}

public void Stop () {
This.stop = true;
}

@Override
public void Run () {
while (!stop) {
try {
Selector.select (1000);
Set<selectionkey> selectionkeys= Selector.selectedkeys ();
Selectionkey Key=null;
Iterator<selectionkey> it= selectionkeys.iterator ();
while (It.hasnext ()) {
Key=it.next ();
It.remove ();
try{
Handleinput (key);
}catch (Exception e) {
E.printstacktrace ();
}
}
} catch (Exception e) {
E.printstacktrace ();
}
}
if (selector!=null) {
try{
Selector.close ();
}catch (Exception e) {
E.printstacktrace ();
}
}
}

public void Handleinput (Selectionkey key) throws ioexception{
if (Key.isvalid ()) {
if (key.isacceptable ()) {
Serversocketchannel ssc= (Serversocketchannel) Key.channel ();
Socketchannel sc= ssc.accept ();
Sc.configureblocking (FALSE);
Sc.register (selector, selectionkey.op_read);
UserInfo = new UserInfo ();
Userinfo.setusername (sc.getremoteaddress () + "");
Userinfo.setsocket (Sc.socket ());//save user information here is key, especially to save its socket information corresponding to name
Users.put (sc.getremoteaddress () + "", userinfo);
System.out.println (users);
}
if (key.isreadable ()) {
Socketchannel sc= (Socketchannel) Key.channel ();
Bytebuffer readbuffer=bytebuffer.allocate (1024);
int Readbytes=sc.read (readbuffer);
if (readbytes>0) {
Readbuffer.flip ();
Byte[] Bytes=new byte[readbuffer.remaining ()];
Readbuffer.get (bytes);
String body=new string (bytes, "UTF-8");
String name=body.substring (0,body.lastindexof (".") +8);
System.out.println (body);
Socketchannel soc= users.get (name). Getsocket (). Getchannel ();

Dowrite (Soc,body);


}
}
}
}

private void Dowrite (Socketchannel channel,string response) throws ioexception{
if (Response!=null&&response.trim (). Length () >0) {
Byte[] Bytes=response.getbytes ();
Bytebuffer bf=bytebuffer.allocate (bytes.length);
Bf.put (bytes);
Bf.flip ();
Channel.write (BF);
}
}

public static void Main (string[] args) {
Nioserver ns=new Nioserver (8088);
Ns.run ();
}

}

Java,socket,nio Essay Records

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.