Java Very Simple Sever / Client Example
Some basic code to demonstrate the client/sever link up, this code can be simply modified in to a simple chat room application.
SERVER.java
import java.io.DataOutput;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
class server
{
public static void main(String args[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcome = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcome.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received : "+clientSentence);
capitalizedSentence=clientSentence.toUpperCase()+"\n";
outToClient.writeBytes(capitalizedSentence);
}
}
}
CLIENT.java
import java.io.DataOutput;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
class client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
No comments:
Post a Comment