Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions TCP-basics/server.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// A Java program for a Server
import java.net.*;
import java.io.*;

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);
System.out.println("Server started");

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

socket = server.accept();
System.out.println("Client accepted");

// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);

}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");

// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])
{
Server server = new Server(5000);
}
}