Several classes related to socket programming:
InetAddress
Socket: Used on client
ServerSocket: Used on server side
One. Point to Point Communication
Server side:
Package server;
import java.io.*;
import java.net.*;
public class Server {
private int port;
public Server (int port) {
This.port=port;
start ();
}
//Converts the information received from the client into uppercase
Public String process (string line) {
return Line.touppercase ();
}
public void Start () {
try{
//Socket creation based on port
serversocket myscoket=new ServerSocket (port);
//Display connection Information
System.out.println ("Server boot complete, listening port in" +port);
System.out.println ("Waiting for customer connections ...");
//Suspend waiting for customer's request
Socket connection=myscoket.accept ();
Test
System.out.println ("customer sends a connection request ...");
//Get the data stream to read the client
BufferedReader in=new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
//Get the data output stream written to the client, true to automatically refresh
printwriter out=new PrintWriter (Connection.getoutputstream (), true);
//Send a welcome message to the customer
out.println ("Hello, server connection successful!") ");
out.println ("Enter bye disconnect from server");
Boolean done=false;
while (!done) {
//Read the contents of the client
String line=in.readline ();
if (line==null) {
done=true;
}else{
//Displays the information sent by the client from the server side
System.out.println ("Content from client" +line);
//Information processing
String message=process (line);
//Send message to Client
out.println ("Information sent from the server port" +message);
if (Line.trim (). Equals ("BYE"))
done=true;
}
}
//Turn off communication
Connection.close ();
}catch (Exception e) {
System.out.println (e);
}
}
}
Package server;
public class Serverdemo {
/**
* @param args
*/
public static void Main (string[] args) {
//TODO auto-generated method stub
if (args.length!=1) {
System.out.println ("Run as: Java Server < port number >");
return;
}
try{
//Get the port number
int port=integer.parseint (args[0]);
Server myserver=new Server (port);
}catch (Exception e) {
System.out.println (e);
}
}
}