Example of a JAVA SOCKET server/client can send messages from any party at any time __java

Source: Internet
Author: User
Tags flush readline

On the Internet to find a number of examples are the client must first send a message, the server to reply to a message. This approach is inconvenient for the server to actively send messages to clients.

Research, found that the main reason is because of the BufferedReader ReadLine method will block the thread there, swap datainputstream and dataoutputstream can be achieved.

Server-side code:

Import java.net.*;
Import java.io.*;

Import Test. Configuration;

/**
* @author Chenyi
*
*/

public class TCPServer {

 public TCPServer () {
  try {
   serversocket server = new ServerSocket ();
   server.bind New Inetsocketaddress (Configuration.tcpip,
      Configuration.tcpport));
   while (True) {
    //transfer location Change single user or Multi user
    tcpserverthread TCT = new Tcpserverthread (server.accept ());
    tct.start ();
   }
  } catch (IOException ex) {
   ex.printstacktrace ();
 &NBSP}
 }

public static void Main (string[] args) throws IOException {
if (args.length = = 2) {
try {
Configuration.tcpip = Args[0];
Configuration.tcpport = Integer.parseint (args[1]);
catch (Exception ex) {
System.exit (1);
}
}
New TCPServer ();
}
}

Import java.net.*;
Import java.io.*;

/**
* @author Chenyi
*
*/
public class Tcpserverthread extends Thread {

Socket client;
volatile static int num = 0;

Public Tcpserverthread (Socket c) {
This.client = C;
System.out.println (Client.getinetaddress (). Gethostaddress () + ":"
+ Client.getport ());
}

@Override
public void Run () {
int i = ++num;
System.out.println ("Thread" + i + "is starting");
try {
DataInputStream in = new DataInputStream (Client.getinputstream ());
DataOutputStream out = new DataOutputStream (
Client.getoutputstream ());
BufferedReader wt = new BufferedReader (New InputStreamReader (
system.in));
Mutil User but can parallel
while (true) {
if (in.available () > 0) {
String str = IN.READUTF ();
System.out.println (str);
Out.writeutf (str + "has receive ...");
Out.flush ();
if (Str.equals ("End") | | (null = = str)) {
Break
}
} else {
if (Wt.ready ()) {
String str = wt.readline ();
Out.writeutf (str);
Out.flush ();
}else{
try {
Client.sendurgentdata (0xFF);
Thread.Sleep (100);
catch (Exception ex) {
Ex.printstacktrace ();
Break
}
}
}
}
Client.close ();
catch (Exception ex) {
Ex.printstacktrace ();
finally {
System.out.println ("Thread" + i++ + "is ending");
}
}
}

Client code:

Import java.net.*;
Import java.io.*;

Import Test. Configuration;

/**
* @author Chenyi
*
*/
public class TcpClient {

static socket socket;

public static void Main (string[] args) throws Exception {
if (args.length = = 2) {
try {
Configuration.tcpip = Args[0];
Configuration.tcpport = Integer.parseint (args[1]);
catch (Exception ex) {
System.exit (1);
}
}
Socket = new socket ();
Socket.connect (New Inetsocketaddress (CONFIGURATION.TCPIP,
Configuration.tcpport), 2000);

DataInputStream in = new DataInputStream (Socket.getinputstream ());
DataOutputStream out = new DataOutputStream (Socket.getoutputstream ());
BufferedReader wt = new BufferedReader (new InputStreamReader (system.in));

while (true) {

if (Wt.ready ()) {
String str = wt.readline ();
Out.writeutf (str);
Out.flush ();

if (Str.equals ("End")) {
Break
}

} else {
try {
Socket.sendurgentdata (0xFF);
Thread.Sleep (100);
catch (Exception ex) {
Ex.printstacktrace ();
Break
}
}
if (in.available () > 0)
System.out.println (In.readutf ());
}
Socket.close ();
}
}

The

Implements a connection request that can accept multiple clients at the same time, and the client/server can enter and send a string from the command line at any time, and the other end throws an exception when it closes (you can increase the handling of the exception).

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.