Here are my 2 different programs that connect to each other:
SERVER
package authenticateddns;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class Server {
public static final int PORT = 4444;
int clientNumber;
static String[][] url = new String[8][2];
public static void main(String args[]) throws IOException {
url[0][0] = "www.google.com";
url[0][1] = "172.217.11.174";
url[1][0] = "www.facebook.com";
url[1][1] = "31.13.77.36";
url[2][0] = "www.youtube.com";
url[2][1] = "74.125.65.91";
url[3][0] = "www.wikipedia.org";
url[3][1] = "91.198.174.192";
url[4][0] = "www.twitter.com";
url[4][1] = "199.59.149.230";
url[5][0] = "www.amazon.com";
url[5][1] = "72.21.211.176";
url[6][0] = "www.yahoo.com";
url[6][1] = "98.137.149.56";
url[7][0] = "www.abc.com";
url[7][1] = "199.181.132.250";
new Server().runServer();
}
public void runServer() throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up and ready for connection...");
while (true) {
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
Socket socket = serverSocket.accept();
pool.submit(() -> new ServerThread(socket, clientNumber, url).start());
System.out.println("New client has joined");
clientNumber++;
}
}
}
SERVERTHREAD
package authenticateddns;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket socket;
String clientName;
int clientN;
String url[][];
byte[] message = new byte[4];
ServerThread(Socket socket, int clientNumber, String[][] url)
{
this.socket = socket;
clientN = clientNumber;
this.url=url;
message[0]=1;
message[1]=2;
message[2]=3;
message[3]=4;
}
public void run()
{
try
{
String userURL;
String ip = "";
clientName = "Client" + clientN;
//this is from the server
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//this is from the client
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
//dout.writeInt(message.length);
//dout.write(message);
//this reads in from client
while(true)
{
if((userURL = bufferedReader.readLine()) != null)
{
userURL = userURL.replace("\n", "").replace("\r", "");
for(int i = 0; i < 8; i++)
{
if(url[i][0].equals(userURL))
{
ip = url[i][1];
break;
}
if(!url[i][0].equals(userURL)&&i==7)
{
ip = "IP Address not found";
}
}
//System.out.println(clientName);
System.out.println(" " + clientName + ": Desired URL: " + userURL);
System.out.println(" " + clientName + ": Sending IP: " + ip);
System.out.println("");
//send this to client
printWriter.println("Server Recieved Message");
printWriter.println(ip);
dout.write(message);
System.out.println("worked");
}
//socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
AND THEN YOU HAVE THE CLIENT PROGRAM
package client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) throws IOException
{
//InetAddress localIP;
//localIP = InetAddress.getLocalHost();
//Socket socket = new Socket("10.0.36.89", 4444);
Socket socket = new Socket("10.1.43.10", 4444);
String ip;
String confirm;
int length;
// from client
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
BufferedReader buffedReader = new java.io.BufferedReader(new InputStreamReader(System.in));
//from server
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream din = new DataInputStream(socket.getInputStream());
while(true)
{
//this sends input
System.out.print("Enter Destired URL: ");
String readerInput = buffedReader.readLine();
readerInput = readerInput.replace("Enter Destired URL: ", "");
printWriter.println(readerInput);
if((confirm = bufferedReader.readLine()) != null)
{
System.out.println(confirm);
}
//this reads in from server
if((ip = bufferedReader.readLine()) != null)
{
System.out.println("Server returns IP Address: " + ip);
System.out.println("");
}
int j = 4;
byte[] message = new byte[4];
if(j>0)
{
din.readFully(message, 0, 4); // read the message
j=j-1;
}
for(int i = 0; i < 4; i++)
{
System.out.print(message[i]);
}
}
}
}
The issue is that the client is not receiving the byte array. It only works if you run the Server program in debugger and put a breakpoint on where it writes to Client.
Does anyone have any ideas?
Related
The sequence numbers aren't working as the int value seems to reset to 0 - or setting it again in the second method returns an error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Client3.sendThenReceive(Client3.java:106)
at Client3.stopAndWait(Client3.java:69)
at Client3.main(Client3.java:41)
This is the client:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.nio.*;
public class Client3 {
private DatagramSocket datagramSocket;
private InetAddress inetAddress;
private byte [] buffer;
private int initialSequenceNumber = 100;
private int sequenceNumber;
private int testSN;
private static final int port = 1234;
private static final int BUFFER_SIZE = 1024;
private static final String HOSTNAME = "localhost";
private static String message;
public Client3(DatagramSocket datagramSocket, InetAddress inetAddress) {
this.datagramSocket = datagramSocket;
this.inetAddress = inetAddress;
}
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName(HOSTNAME);
Client3 client = new Client3(datagramSocket, inetAddress);
System.out.println("Send datagram packets to a server");
Scanner scanner = new Scanner(System.in);
message = (scanner.nextLine() + " Umbrella");
scanner.close();
client.stopAndWait();
}
public void stopAndWait() throws IOException {
Client3 client = new Client3(datagramSocket, inetAddress);
sequenceNumber = initialSequenceNumber;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
toSend.writeInt(sequenceNumber);
buffer = test.toByteArray();
DatagramPacket testConnection = new DatagramPacket(buffer, buffer.length, inetAddress, port);
System.out.println("testConnection sent, waiting for confirmation.");
datagramSocket.send(testConnection);
datagramSocket.receive(testConnection);
ByteArrayInputStream confirmConnection = new ByteArrayInputStream(testConnection.getData());
DataInputStream dis = new DataInputStream(confirmConnection);
int SN = dis.readInt();
//test code to show the received data to the console
//System.out.println(SN);
if (SN == sequenceNumber) {
System.out.println("Confirmation received. Proceeding to Message delivery.");
//testSN = sequenceNumber;
//System.out.println("test: " + testSN + " SN: " + sequenceNumber);
client.sendThenReceive();
}
else {
System.out.println("error - incorrect sequence number.");
}
}
public void sendThenReceive() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
// Changing the variable here results in error and termination
//Is it because it is in the method?
//int newNumber = 101;
//testSN = 101;
//sequenceNumber = 101;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
System.out.println("test: " + testSN + " SN: " + sequenceNumber);
toSend.writeInt(sequenceNumber);
toSend.writeUTF(message);
buffer = test.toByteArray();
System.out.println(message + " " + sequenceNumber);
DatagramPacket sentMessage = new DatagramPacket(buffer, buffer.length, inetAddress, port);
datagramSocket.send(sentMessage);
datagramSocket.receive(sentMessage);
ByteArrayInputStream test2 = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test2);
int SN = dis.readInt();
String messageFromServer = dis.readUTF();
if (SN == 101) {
System.out.println("The server says you said: " + messageFromServer);
sequenceNumber++;
Scanner newScanner = new Scanner(System.in);
message = (newScanner.nextLine() + " Umbrella");
newScanner.close();
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
} scanner.close();
}
}
And this is the server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.io.*;
import java.net.*;
import java.nio.*;
public class Server3 {
private DatagramSocket datagramSocket;
private byte[] dataForSend = new byte[256];
byte[] receiveData = new byte[ dataForSend_SIZE ];
//byte[] dataForSend = new byte[ dataForSend_SIZE ];
private int initialSequenceNumber = 100;
private int sequenceNumber;
private static final int port = 1234;
private static final int dataForSend_SIZE = 1024;
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(port);
Server3 server = new Server3(datagramSocket);
System.out.println("Server Operational");
server.testConnection();
}
public Server3(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
public void testConnection() throws IOException {
while (true) {
try {
sequenceNumber = initialSequenceNumber;
DatagramPacket receivedMessage = new DatagramPacket (receiveData, receiveData.length);
datagramSocket.receive(receivedMessage);
InetAddress inetAddress = receivedMessage.getAddress();
int port = receivedMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(receivedMessage.getData());
DataInputStream dis = new DataInputStream(test);
int a10 = dis.readInt();
System.out.println("SN read from Datagram: " + a10);
if ( a10 == sequenceNumber) {
System.out.println("Connection Test Successfully Received.");
ByteArrayOutputStream confirmConnection = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(confirmConnection);
toSend.writeInt(sequenceNumber);
dataForSend = confirmConnection.toByteArray();
DatagramPacket testConnection = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(testConnection);
System.out.println("'confirmConnection' has been sent.");
sequenceNumber++;
receiveThenSend();
}
else {
System.out.println("error - incorrect sequence number."); }
}
finally {
}
}
}
public void receiveThenSend() throws IOException {
while (true) {
try {
sequenceNumber = 101;
DatagramPacket sentMessage = new DatagramPacket(receiveData, receiveData.length);
datagramSocket.receive(sentMessage);
InetAddress inetAddress = sentMessage.getAddress();
int port = sentMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test);
int SN = dis.readInt();
System.out.println("SN received: " + SN);
System.out.println("SN on File: " + sequenceNumber);
String messageFromClient = dis.readUTF();
if (SN == sequenceNumber) {
//String messageFromClient = new String(sentMessage.getData(), 0, sentMessage.getLength());
System.out.println("SN: Match.");
System.out.println("Message from Client: " + messageFromClient);
System.out.println("Response sent.");
ByteArrayOutputStream serverResponse = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(serverResponse);
toSend.writeInt(101);
toSend.writeUTF(messageFromClient);
dataForSend = serverResponse.toByteArray();
sentMessage = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(sentMessage);
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
Can anyone see why these would be resetting, please?
The Exception you're getting is caused by closing the Scanner. When a Scanner instance is closed, it closes the underlying stream which is System.in in your case.
So next time when you create the Scanner, it's created over a closed stream and .nextLine() throws the exception you're seeing.
Here's a snippet that reproduces the issue:
Scanner s1 = new Scanner(System.in);
s1.close();
Scanner s2 = new Scanner(System.in);
s2.nextLine(); //Exception in thread "main" java.util.NoSuchElementException: No line found
I am learning Java networking and am trying to implement a simple UDP server-client program which exchanges messages between server and client. The program is working, but when I print the buffer, a lot of newlines get printed. What am I doing wrong? Here is my code for the server:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.net.SocketException;
class Q1Server {
private DatagramSocket ds;
private byte[] buff1, buff2;
private DatagramPacket dp1 = null, dp2 = null;
private InetAddress clientIP;
private int clientPort;
public Q1Server() throws SocketException{
ds = new DatagramSocket(1234);
buff1 = new byte[10000];
buff2 = null;
while(true) {
try {
dp1 = new DatagramPacket(buff1, buff1.length);
System.out.println("Waiting for connection...");
ds.receive(dp1);
System.out.print(new String(buff1, "UTF-8"));
buff1 = new byte[10000];
clientIP = dp1.getAddress();
clientPort = dp1.getPort();
System.out.println("Connected to IP: " + clientIP + " Port: " + clientPort);
buff2 = ("Thanks for connecting to the server!!!").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, clientIP, clientPort);
ds.send(dp2);
String cl = "";
while (!cl.equals("close")) {
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println("here");
cl = new String(buff1, "UTF-8");
buff1 = new byte[10000];
System.out.println("Client: " + cl);
}
buff2 = ("Closing...\nGoodbye!!!").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, clientIP, clientPort);
ds.send(dp2);
} catch(IOException i) {
i.printStackTrace();
}
}
}
public static void main(String[] args) throws SocketException {
Q1Server server = new Q1Server();
}
}
And here is the code for client:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
class Q1Client {
private DatagramSocket ds;
private Scanner scanner;
private InetAddress ip;
private byte[] buff1, buff2;
private DatagramPacket dp1 = null, dp2 = null;
public Q1Client() throws SocketException, UnknownHostException {
ds = new DatagramSocket();
ip = InetAddress.getLocalHost();
buff1 = new byte[10000];
buff2 = null;
scanner = new Scanner(System.in);
try {
buff2 = ("Start").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, ip, 1234);
ds.send(dp2);
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println(new String(buff1, "UTF-8"));
buff1 = new byte[10000];
String msg = "";
while(!msg.equals("close")) {
System.out.println("here");
msg = scanner.nextLine();
System.out.println("Typed: " + msg);
buff2 = msg.getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, ip, 1234);
ds.send(dp2);
}
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println(new String(buff1, "UTF-8"));
} catch(IOException i) {
i.printStackTrace();
}
}
public static void main(String[] args) throws SocketException, UnknownHostException{
Q1Client client = new Q1Client();
}
}
I think the problem may be due to the size of the buffer. The byte buffer array is pre-initialized with the size that large than the actual text being sent. But what is the other way to do it? How do I know the size of the buffer dynamically?
I am making a simple java chatbox using sockets. When I run many clients on same computer, everything's alright, but when I try it on different PCs, they don't share the information. How could I fix that? I guess that has something to do with port and host, not sure though. My connecting method is below.
public static void Connect() {
try {
final int port = 444;
String hostname = "";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
final String host = "Laurie-PC";
Socket sock = new Socket(host, port);
System.out.println("You connected to " + host);
ChatClient = new A_Chat_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(UserName);
out.flush();
Thread X = new Thread(ChatClient);
X.start();
} catch (Exception E) {
System.out.println(E);
JOptionPane.showMessageDialog(null, "Server not responding");
System.exit(0);
}
}
this is the server code
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class A_Chat_Server {
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
try {
final int port = 444;
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for clients...");
A_Chat_Client_GUI.main(args);
while (true) {
Socket sock = server.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
AddUserName(sock);
A_Chat_Server_Return chat = new A_Chat_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch (Exception X) {
System.out.println(X);
}
}
public static void AddUserName(Socket X) throws IOException {
Scanner input = new Scanner(X.getInputStream());
String UserName = input.nextLine();
CurrentUsers.add(UserName);
for (int i = 0; i < A_Chat_Server.ConnectionArray.size(); i++) {
Socket temp_sock = A_Chat_Server.ConnectionArray.get(i);
PrintWriter out = new PrintWriter(temp_sock.getOutputStream());
out.println("????1!!!!!!???#######22" + CurrentUsers);
out.flush();
}
}
}
Good evening, I got this server and client here.
WebServer
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class WebServer {
public static void main(String[] args) throws Exception {
HttpServer http = HttpServer.create(new InetSocketAddress(8000), 0);
http.createContext("/test", new MyHandler());
http.setExecutor(null); // creates a default executor
http.start();
//NimServer nimserver = new NimServer(32778);
//nimserver.serve();
}
static class MyHandler implements HttpHandler {
//AtomicInteger atomicInteger = new AtomicInteger(0);
//int theValue = atomicInteger.get();
#Override
public void handle(final HttpExchange t) throws IOException {
final String response;
final String requestMethod = t.getRequestMethod();
if ("GET".equals(requestMethod)) {
// response = String.format("Besuche: %d%n", atomicInteger.addAndGet(1));
}
else if ("POST".equals(requestMethod)) {
// atomicInteger.set(0);
int clientno = new DataInputStream(t.getRequestBody()).readInt();
System.out.println("Send from Client: " + clientno);
int newclientno = clientno + 1;
System.out.println("Increased by Server: " + newclientno);
new DataOutputStream(t.getResponseBody()).writeInt(newclientno);
}
else {
throw new IOException("Unsupported method");
}
//t.sendResponseHeaders(200, response.length());
//final OutputStream os = t.getResponseBody();
//os.write(newclientno);
//os.close();
}
}
}
HttpClient
import java.net.*;
import java.io.*;
public class HttpClient {
public static int clientno = 0;
public static void main(String[] args) throws Exception {
//NimMessage clientnumber = new NimMessage();
//clientnumber.nachricht = "Client No: " + clientno;
URL test = new URL("http://localhost:8000/test");
HttpURLConnection connect = (HttpURLConnection) test.openConnection();
connect.setDoOutput(true);
connect.setDoInput(true);
connect.setRequestMethod("POST");
new DataOutputStream(connect.getOutputStream ()).writeInt(clientno);//send int out
int newclientno = new DataInputStream(connect.getInputStream()).readInt();
System.out.println("Send from Server: " + newclientno);
//BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
//String inputLine;
//System.out.println(clientnumber.createJsonNachricht().toString());
//while ((inputLine = in.readLine()) != null)
// System.out.println(inputLine);
//in.close();
}
}
I was able to send the integer clinetno from the client to the server and increase it at the server. But i can not figure out how to send the new integer newclientno back to the client and display it on the console. Any suggestions what i did wrong?
Okay i found my mistake, i had to add an header in the server to complete the connection. Which i already had but did not noticed it.
t.sendResponseHeaders(200, 0);
I got a code from the internet for a Client and Server to communicate in java. I modified it a bit, so that the server and client are able to chat to each other.
Initially my client sends a message to server, then server to client, then client to server and it goes on...(one cannot send more than one message continuously to the other). For this there is a basic code put in the while loop so that the conversation goes on 1 to 1. But as i put the while loop, the message from server is not received by client. If there is no while loop(which i have commented in the code here), then first the message is sent by client to server and then server to client and the program stops.
Please help me in making the chat go endlessly.
//SERVER
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
System.out.println("Server Started and listening to the port 25000");
//while(true){
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Received from client: "+number+"\n");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(s);
bw.flush();
System.out.println("Sent (to " + socket + ") client: "+s+"\n");
//String abc = bufferRead.readLine();
//System.out.println("SAA");
//}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
//CLIENT
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//while(true){
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
String sendMessage = s + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Sent to server: " +sendMessage+"\n");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(socket);
String message = br.readLine();
System.out.println("Received from server: "+message+"\n");
//}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Server implements Runnable {
ServerSocket serversocket;
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in="",out="";
public Server() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
serversocket = new ServerSocket(5000);
System.out.println("Server is waiting. . . . ");
socket = serversocket.accept();
System.out.println("Client connected with Ip " + socket.getInetAddress().getHostAddress());
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t1) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Client says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Client implements Runnable {
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in = "", out = "";
public Client() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
socket = new Socket("localhost", 5000);
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t2) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Server says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Client();
}
}
//server.java
import java.io.*;
import java.net.*;
public class server {
public static void main(String []V){
try{
ServerSocket ss = new ServerSocket(1201);
Socket s = ss.accept();
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgIn = Din.readUTF();
System.out.println(MsgIn);
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
Dout.flush();
}
s.close();
}catch(Exception e){
}
}
}
//clients.java
import java.io.*;
import java.net.*;
import javax.xml.crypto.Data;
public class clients {
public static void main(String []S){
try{
Socket s = new Socket("192.168.0.103",1201);//my pc's ip
//Socket s = new Socket("192.168.0.100",1201);
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
MsgIn = Din.readUTF();
System.out.println(MsgIn);
}
}catch(Exception e){
}
}
}
import java.io.*;
import java.net.*;
class serversvi1
{
public static void main(String svi[])throws IOException
{
try
{
ServerSocket servsock=new ServerSocket(5510);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
System.out.println(fil+" :is file transfer");
File myfile=new File(fil);
while(true)
{
Socket sock=servsock.accept();
byte[] mybytearray=new byte[(int)myfile.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
catch(Exception saranvi)
{
System.out.print(saranvi);
}
}
}
import java.io.*;
import java.net.*;
class clientsvi1
{
public static void main(String svi[])throws IOException
{
try
{
Socket sock=new Socket("localhost",5510);
byte[] bytearray=new byte[1024];
InputStream is=sock.getInputStream();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
FileOutputStream fos=new FileOutputStream(fil);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int bytesread=is.read(bytearray,0,bytearray.length);
bos.write(bytearray,0,bytesread);
System.out.println("out.txt file is received");
bos.close();
sock.close();
}
catch(Exception SVI)
{
System.out.print(SVI);
}
}
}