Sie sind auf Seite 1von 10

1.

CRC Program: -

import java.util.*;
class CRC {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n;

//Accept the input


System.out.println("Enter the size of the data:");
n = scan.nextInt();
int data[] = new int[n];
System.out.println("Enter the data, bit by bit:");
for(int i=0 ; i < n ; i++) {
System.out.println("Enter bit number " + (n-i) + ":");
data[i] = scan.nextInt();
}

// Accept the divisor


System.out.println("Enter the size of the divisor:");
n = scan.nextInt();
int divisor[] = new int[n];
System.out.println("Enter the divisor, bit by bit:");
for(int i=0 ; i < n ; i++) {
System.out.println("Enter bit number " + (n-i) + ":");
divisor[i] = scan.nextInt();
}

// Divide the inputted data by the inputted divisor


// Store the remainder that is returned by the method
int remainder[] = divide(data, divisor);
for(int i=0 ; i < remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println("\nThe CRC code generated is:");

for(int i=0 ; i < data.length ; i++) {


System.out.print(data[i]);
}
for(int i=0 ; i < remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println();

// Create a new array


// It will have the remainder generated by the above method appended
// to the inputted data
int sent_data[] = new int[data.length + remainder.length - 1];
System.out.println("Enter the data to be sent:");
for(int i=0 ; i < sent_data.length ; i++) {
System.out.println("Enter bit number " + (sent_data.length-i)
+ ":");
sent_data[i] = scan.nextInt();
}
receive(sent_data, divisor);
}

static int[] divide(int old_data[], int divisor[]) {


int remainder[] , i;
int data[] = new int[old_data.length + divisor.length];
System.arraycopy(old_data, 0, data, 0, old_data.length);
// Remainder array stores the remainder
remainder = new int[divisor.length];
// Initially, remainder's bits will be set to the data bits
System.arraycopy(data, 0, remainder, 0, divisor.length);

// Loop runs for same number of times as number of bits of data


// This loop will continuously exor the bits of the remainder and
// divisor
for(i=0 ; i < old_data.length ; i++) {
System.out.println((i+1) + ".) First data bit is : "
+ remainder[0]);
System.out.print("Remainder : ");
if(remainder[0] == 1) {
// We have to exor the remainder bits with divisor bits
for(int j=1 ; j < divisor.length ; j++) {
remainder[j-1] = exor(remainder[j], divisor[j]);
System.out.print(remainder[j-1]);
}
}
else {
// We have to exor the remainder bits with 0
for(int j=1 ; j < divisor.length ; j++) {
remainder[j-1] = exor(remainder[j], 0);
System.out.print(remainder[j-1]);
}
}
// The last bit of the remainder will be taken from the data
// This is the 'carry' taken from the dividend after every step
// of division
remainder[divisor.length-1] = data[i+divisor.length];
System.out.println(remainder[divisor.length-1]);
}
return remainder;
}
static int exor(int a, int b) {
// This simple function returns the exor of two bits
if(a == b) {
return 0;
}
return 1;
}

static void receive(int data[], int divisor[]) {


// This is the receiver method
// It accepts the data and divisor (although the receiver already has
// the divisor value stored, with no need for the sender to resend it)
int remainder[] = divide(data, divisor);
// Division is done
for(int i=0 ; i < remainder.length ; i++) {
if(remainder[i] != 0) {
// If remainder is not zero then there is an error
System.out.println("There is an error in received data...");
return;
}
}
//Otherwise there is no error in the received data
System.out.println("Data was received without any error.");
}
}

2. HTTP Webserver Program: -


import java.util.*;
import java.io.*;
import java.net.*;

//A Webserver waits for clients to connect, then starts a seperate thread to handle the request.

public class MyWebServer2


{
private static ServerSocket serverSocket;

public static void main(String[] args) throws IOException


{
serverSocket=new ServerSocket(8000); //Start, listen on port 8000
while(true)
{
try
{
Socket s=serverSocket.accept(); //Wait for a client to connect
new ClientHandler(s); //Handle the client in a seperate thread
}
catch (Exception x)
{
System.out.println(x);
}
}
}
}

//A ClientHandler reads an HTTP request and responds

class ClientHandler extends Thread


{
private Socket socket;

//The accepted socket from the Webserver


//Start the thread in the constructor
public ClientHandler(Socket s)
{
socket=s;
start();
}

//Read the HTTP request, respond and close the connection


public void run()
{
try
{
//Open connection to the socket

BufferedReader in=new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintStream out=new PrintStream(new
BufferedOutputStream(socket.getOutputStream()));

//Read filename from first input line "GET/filename.html..."


//Or if not in this format, treat as a file not found.

String s=in.readline();
System.out.println(s); //Log the request

//Attempt to serve the file. Catch FileNotFoundException and


//Return an HTTP error "404 Not Found". Treat invalid request the same way

String filename="";
String Tokenizer st=new StringTokenizer(s);
try
{
//Parse the filename from the GET command
if(st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET")
&& st.hasMoreElements())
filename=st.nextToken();
else
throw new FileNotFoundException();

//Bad request
//Append trailing "/" with "index.html"
if(filename.endsWith("/"))
filename+="index.html";

//Remove leading / from filename

while (filename.indexOf("/")==0)
filename=filename.substring(1);

//Replace "/" with "\" in path for PC-based servers

filename=filename.replace('/', File.seperator.charAt(0));

//check for illegal characters to prevent access to superdirectories

if(filename.indexOf("..")>=0 || filename.indexOf(':')>=0 ||
filename.indexOf('|')>=0)
throw new FileNotFoundException();

//If a directory is requested and the trailing / is missing,


//send the client an HTTP request to append it.
//(This is necessary for relative links to work correctly in the client).

if(new File(filename).isDirectory())
{
filename=filename.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n"+"Location:
/"+filename+"/\r\n\r\n");
out.close();
return;
}

//Open the file(may throw FileNotFoundException)

InputStream f=new FileInputStream(filename);

//Determine the MIME type and print HTTP header

String mimeType="text/plain";
if(filename.endswith(".html") || filename.endswith(".htm"))
mimeType="text/html";
else if(filename.endswith(".jpg") || filename.endswith(".jpeg"))
mimeType="image/jpeg";
else if(filename.endswith(".gif"))
mimeType="image/gif";
else if(filename.endswith(".class"))
mimeType="application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n"+"Content-type:
"mimeType+"\r\n\r\n");

//Send file contents to client, then close the connection

byte[] a=new byte[4096];


int n;
while((n=f.read(a))>0)
out.write(a,0,n);
out.close();
}

catch (FileNotFoundException x)
{
out.println("HTTP/1.0 404 Not Found\r\n"+"Content-type:
text/html\r\n\r\n"+"<html><head></head><body>"+filename+"not found</body></html>\n");
out.close;
}
}
catch (IOException x)
{
System.out.println(x);
}
}
}

3. TCP Client

import java.io.*;
import java.net.*;
class client{

public static void main(String args[]) throws Exception{


String sentence;
String modifiedSentence;

BufferedReader inFromUser = new BufferedReader(new


InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1",6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("enter message:");
sentence = inFromUser.readLine();

while(!(sentence.equals(""))){
outToServer.writeBytes(sentence+"\n");
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
System.out.println("enter ur msg");
sentence = inFromUser.readLine();}
clientSocket.close();}
}

4. TCP Server

import java.io.*;
import java.net.*;
import java.lang.*;

class server{
public static void main(String args[]) throws Exception{
String clientSentence;
String capitalizedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
try{
while(!(clientSentence.equals(""))){
System.out.println("from client:"+clientSentence);
String UserReply = inFromUser.readLine();
capitalizedSentence = "reply from server"+ UserReply +"\n";
outToClient.writeBytes(capitalizedSentence);
clientSentence = inFromClient.readLine();}
}
catch(Exception e){
System.out.println("chat ended");
welcomeSocket.close();
}}}}

5. TCP Multithreaded Server: -


import java.io.*;
import java.net.*;
import java.lang.*;

class server{
public static void main(String args[]) throws Exception{
String clientSentence;
String capitalizedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
ServerSocket welcomeSocket = new ServerSocket(6789);

while(true){

Socket connectionSocket = welcomeSocket.accept();


mlt object = new mlt(connectionSocket);
object.start();

}
}
}

class mlt extends Thread


{
Socket connectionSocket;
String clientSentence;
String capitalizedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));

mlt (Socket abc)


{
connectionSocket = abc;
}

public void run()


{
try{

BufferedReader inFromClient = new BufferedReader(new


InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
try{
while(!(clientSentence.equals(""))){
System.out.println("from client:"+clientSentence);
String UserReply = inFromUser.readLine();
capitalizedSentence = "reply from server"+ UserReply +"\n";
outToClient.writeBytes(capitalizedSentence);
clientSentence = inFromClient.readLine();}
}
catch(Exception e){
System.out.println("chat ended");
}

}
catch(Exception e){
System.out.println("Exception is found");
}}}
6. UDP Client

import java.net.*;

class MyUDPC
{
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];

public static void TheClient() throws Exception


{while(true)
{DatagramPacket p = new DatagramPacket(buffer,buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(),0,p.getLength()));
}
}
public static void main(String args[]) throws Exception
{ds = new DatagramSocket(clientPort);
TheClient();
}}

7. UDP Server

import java.net.*;
class MyUDPS
{
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];

public static void TheServer() throws Exception


{int pos = 0;
System.out.println("Enter Text (1 to exit) : \n");
while(true)
{int c = System.in.read();
switch(c)
{case '1':
System.out.println("Server Quits.");
break;
case '\r':
break;
case '\n':
ds.send(new
DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
pos = 0;
break;
default:
buffer[pos++] = (byte)c;
}}}

public static void main(String args[]) throws Exception


{ds = new DatagramSocket(serverPort);
TheServer();
ds.close();
}
}

Das könnte Ihnen auch gefallen