KEMBAR78
Socket Programming | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
5 views5 pages

Socket Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Socket Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

// Demonstrating Server-side Programming

import java.net.*;

import java.io.*;

public class Server {

// Initialize socket and input stream

private Socket s = null;

private ServerSocket ss = null;

private DataInputStream in = null;

// Constructor with port

public Server(int port) {

// Starts server and waits for a connection

try

ss = new ServerSocket(port);

System.out.println("Server started");

System.out.println("Waiting for a client ...");

s = ss.accept();

System.out.println("Client accepted");

// Takes input from the client socket

in = new DataInputStream(

new BufferedInputStream(s.getInputStream()));
String m = "";

// Reads message from client until "Over" is sent

while (!m.equals("Over"))

try

m = in.readUTF();

System.out.println(m);

catch(IOException i)

System.out.println(i);

System.out.println("Closing connection");

// Close connection

s.close();

in.close();

catch(IOException i)

System.out.println(i);

public static void main(String args[])


{

Server s = new Server(5000);

// Demonstrating Client-side Programming


import java.io.*;

import java.net.*;

public class Client {

// Initialize socket and input/output streams

private Socket s = null;

private DataInputStream in = null;

private DataOutputStream out = null;

// Constructor to put IP address and port

public Client(String addr, int port)

// Establish a connection

try {

s = new Socket(addr, port);

System.out.println("Connected");

// Takes input from terminal

in = new DataInputStream(System.in);
// Sends output to the socket

out = new DataOutputStream(s.getOutputStream());

catch (UnknownHostException u) {

System.out.println(u);

return;

catch (IOException i) {

System.out.println(i);

return;

// String to read message from input

String m = "";

// Keep reading until "Over" is input

while (!m.equals("Over")) {

try {

m = in.readLine();

out.writeUTF(m);

catch (IOException i) {

System.out.println(i);

// Close the connection

try {

in.close();
out.close();

s.close();

catch (IOException i) {

System.out.println(i);

public static void main(String[] args) {

Client c = new Client("127.0.0.1", 5000);

You might also like