0% found this document useful (0 votes)
6 views6 pages

Java Client-Server Socket Example

Uploaded by

Steves Fall
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)
6 views6 pages

Java Client-Server Socket Example

Uploaded by

Steves Fall
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

// A Java program for a Client

import [Link].*;
import [Link].*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;

// constructor to put ip address and port


public Client(String address, int port)
{ // establish a connection
try
{
socket = new Socket(address, port);
[Link]("Connected");
// takes input from terminal
input = new DataInputStream([Link]);

// sends output to the socket


out = new
DataOutputStream([Link]());
}
catch(UnknownHostException u)
{
[Link](u);
}
catch(IOException i)
{
[Link](i);
}

// string to read message from input


String line = "";
// keep reading until "Over" is input
while (![Link]("Over"))
{
try
{
line = [Link]();
[Link](line);
}
catch(IOException i)
{
[Link](i);
}
}
// close the connection
try
{
[Link]();
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}

public static void main(String args[])


{
Client client = new Client("[Link]", 5000);
}
}
// A Java program for a Server
import [Link].*;
import [Link].*;

public class Server


{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port


public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
[Link]("Server started");

[Link]("Waiting for a client ...");

socket = [Link]();
[Link]("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new
BufferedInputStream([Link]()));

String line = "";

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


while (![Link]("Over"))
{
try
{
line = [Link]();
[Link](line);

}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");

// close connection
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}

public static void main(String args[])


{
Server server = new Server(5000);
}
}

You might also like