I just tried to build a simple server and client - java

Both ran successfully, but they skipped some parts, I don't know why. Here are the codes
Client:
package echoapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class SimpleEchoClient {
public static void main(String[] args) throws IOException{
System.out.println("Simple Echo Client");
try {
System.out.println("Waiting for connection.....");
InetAddress localAddress = InetAddress.getLocalHost();
try (Socket clientSocket = new Socket(localAddress, 6000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))){
System.out.println("Connected to server");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter text: ");
String inputLine = scanner.nextLine();
if ("quit".equalsIgnoreCase(inputLine)) {
break;
}
out.println(inputLine);
String response = br.readLine();
System.out.println("Server response: " + response);
}
}
} catch (IOException ex) {
// Handle exceptions
}
}
}
Server:
package echoapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleEchoServer {
public static void main(String[] args)throws IOException {
System.out.println("Simple Echo Server");
try (ServerSocket serverSocket = new ServerSocket(6000)){
System.out.println("Waiting for connection.....");
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");
try (BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while((inputLine = br.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(inputLine);
}
}
} catch (IOException ex) {
// Handle exceptions
}
}
}
I should be able to type something in the client and get the response from the server. Like echo. I don't know why how to fix the try block to make all the codes ran through. The parts where the second try has a problem, and I couldn't make the second try block work.

Related

Application chat Client Server - cant send the second message

I'm writing a Client-Server chat application. I can connect them and I can send-receive the first message. But I can't send the second one. I tried to add the do...while() statement for a repetition but It doesn't work. Could some one help me to resolve this problem? Many thanks
This is my server class
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(4999);
Socket serverSocket = server.accept();
System.out.println("client is connected");
String messIn = "", messOut = "";
InputStreamReader serverInput = new InputStreamReader(serverSocket.getInputStream());
BufferedReader serverBufIn = new BufferedReader(serverInput);
Scanner serverScanner = new Scanner(System.in);
PrintWriter serverWriter = new PrintWriter(serverSocket.getOutputStream());
do {
messIn = serverBufIn.readLine();
System.out.println("client : " + messIn);
messOut = serverScanner.nextLine();
serverWriter.print(messOut);
serverWriter.flush();
} while (messOut.equals("quit"));
serverSocket.close();
serverWriter.close();
}
}`
This my client class
`import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 4999);
System.out.println("You are connected. Say something!");
String messIn = "", messOut = "";
InputStreamReader clientInput = new InputStreamReader(clientSocket.getInputStream());
BufferedReader clientBufIn = new BufferedReader(clientInput);
Scanner clientScanner = new Scanner(System.in);
PrintWriter clientWriter = new PrintWriter(clientSocket.getOutputStream());
do {
messOut = clientScanner.nextLine();
clientWriter.println(messOut);
clientWriter.flush();
messIn = clientBufIn.readLine();
System.out.println("server : " + messIn);
} while (messOut.equals("quit"));
clientSocket.close();
clientWriter.close();
}
}
`
try while (true) { }
my code:
public static void newSocket(int port) throws IOException {
ServerSocket ss = new ServerSocket(port);
while (run) {
try {
final Socket socket = ss.accept();
new Thread() {
public void run() {
try {
while (true) {
int i = socket.getInputStream().available();
if (i > 0) {
byte[] bytes = new byte[i];
socket.getInputStream().read(bytes, 0, i);
String s = new String(bytes);
String[] split = s.split("\\|");
if (split.length > 1) {
if (split[0].equals("hello")) {
String msg = split[1];
System.out.println(msg);
PrintStream p = new PrintStream(socket.getOutputStream());
p.println("hello back");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
}
ss.close();
}

Client/Server in java : Program gets stuck upon input of second file name

I am developing code to send multiple file names to server side and then making sure server recieves those contents and writes it to a file in its own folder. Its working well when I type first file name but when I type second file name the code kind of gets stuck.
Here is my client code:-
package fileTransfer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(String[] args) throws UnknownHostException {
try {
Socket clientSock=new Socket("localhost",8888);
//to read from server
BufferedReader br=new BufferedReader(new InputStreamReader(clientSock.getInputStream())); //to read
//to write to server
PrintWriter pw=new PrintWriter(clientSock.getOutputStream(), true);
//for user input
BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileContent=null;
String str=null;
String fileContentLine=null;
while(true){
if((str=br.readLine()).contains("file name")) //recieve echo from server
System.out.println(str);
str=userIn.readLine(); //read user input
fileContent=new BufferedReader(new FileReader(str));
pw.println(str);
while((fileContentLine=fileContent.readLine()) != null){
pw.println(fileContentLine);
}
while((str=br.readLine())!=null)
System.out.println(str);
pw.flush();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
And here is my server code
package fileTransfer;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args){
try {
ServerSocket serverSock=new ServerSocket(8888);
System.out.println("Waiting for client");
Socket connectFromClient=serverSock.accept();
File file=null;
//reading data from client
BufferedReader input=new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));
//will write back to client
PrintWriter pr=new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));
PrintWriter writeToFile=null;
//sending following statements to client
pr.println("Connection established with server! Give a file name");
pr.flush();
String response;
while(true){
while((response=input.readLine()) != null)
{
if(response==null)
break;
else{
System.out.println(response);
if(response.contains(".txt")){
//file=new File("FromClient.txt");
file=new File("FromClient"+response);
if(!file.exists())
file.createNewFile();
writeToFile=new PrintWriter(file);
}
else{
//writeToFile=new PrintWriter(file);
writeToFile.println(response);
}
pr.println("Echo from server -> " + response);
//System.out.println("Adding these contents to a file");
writeToFile.flush();
pr.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It´s getting stuck in the client in this lines:
while ((str = br.readLine()) != null) {
System.out.println(str);
}
Waiting for more server lines.
You have to tell the client when to stop from reading file data from socket stream and jump for the next file. For instance you can send before the content of the file the number of bytes you are going to transfer, you read that number of bytes from the stream and then go for the next file.
I post this modifications of your code as an example, as the idea I want to express.
First I get the total linenumber of the file (I suppose text file), and I send it to server, which knows exactly how many lines to read before jumping to next file.
It can be changed to use the total size of the file in bytes, for instance.
This code is no 100% correct, it works, take it as an example.
Client:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(final String[] args) throws UnknownHostException {
try {
final Socket clientSock = new Socket("localhost", 8888);
// to read from server
final BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); // to
// read
// to write to server
final PrintWriter pw = new PrintWriter(clientSock.getOutputStream(), true);
// for user input
final BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileContent = null;
String str = null;
String fileContentLine = null;
while (true) {
System.out.println("Print filename");
str = userIn.readLine(); // read user input
fileContent = new BufferedReader(new FileReader(str));
pw.println(str);
// first count the line number:
int lineno = 0;
while ((fileContentLine = fileContent.readLine()) != null) {
lineno++;
}
fileContent.close();
//
fileContent = new BufferedReader(new FileReader(str));
pw.println(String.valueOf(lineno));
while ((fileContentLine = fileContent.readLine()) != null) {
pw.println(fileContentLine);
}
for (int i = 0; i < lineno; i++) {
str = br.readLine();
System.out.println(str);
}
pw.flush();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
Server:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(final String[] args) {
try {
final ServerSocket serverSock = new ServerSocket(8888);
System.out.println("Waiting for client");
final Socket connectFromClient = serverSock.accept();
File file = null;
// reading data from client
final BufferedReader input = new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));
// will write back to client
final PrintWriter pr = new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));
PrintWriter writeToFile = null;
// sending following statements to client
pr.println("Connection established with server! Give a file name");
pr.flush();
String response;
while (true) {
final String fileName = input.readLine();
file = new File("FromClient" + fileName);
if (!file.exists()) {
file.createNewFile();
}
writeToFile = new PrintWriter(file);
final String sLineNo = input.readLine();
final int lineno = Integer.parseInt(sLineNo);
for (int i = 0; i < lineno; i++) {
response = input.readLine();
System.out.println(response);
// writeToFile=new PrintWriter(file);
writeToFile.println(response);
pr.println("Echo from server -> " + response);
// System.out.println("Adding these contents to a file");
writeToFile.flush();
pr.flush();
}
writeToFile.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
I Hope to be helpful.

Java TCP Client Server Hangs Up?

I am currently having difficulty understanding why my code is not working. I've included my client and server code below. I've figured out that my problem happens somewhere in the while loops but I'm not sure how to fix it so that it doesn't get stuck. I've searched around the forum for a while and some said adding a newline character would fix it, but I'm still having trouble.
My main question is how can I avoid the process from getting stuck and not communicating properly. Can anybody out there point me in the right direction?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print('\n');
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
-----------------------------------------------------------------
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print('\n');
}
System.out.println("Client disconnected");
r.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Both ends are reading until EOS and neither is closing until after that. So you have a classic deadlock. You need to rethink your application protocol.
You also need to tell your PrintStream or PrintWriter to autoflush, or else call flush() yourself, but this is a relatively minor matter compared to the mistake above.
You should use autoflush on your PrintWriters like this:
PrintStream w = new PrintStream(cs.getOutputStream(),true);
You can setup a PROTOCOL to end the communication something like this:
In your client:
w.println("[END]");
In your server:
while (!(line = r.readLine()).equals("[END]")) {
Hope this helps:
Check the comments
And be sure that you get Client Connected on console of server side
CLIENT SIDE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print("\n"); // enter new line
w.flush();// flush the outputstream
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
SERVER SIDE
----------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print("\n");// entering new line
}
System.out.println("Client disconnected");
r.close();
w.close();// close w
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

java tcp socket can't send file to server side

I'm new to java socket programming, this program allows TCP server to have a multi-thread that can run concurrently. I try to send the txt file from one client(has another client that will sent file at the same time) to the server side and ask server to send "ok" status message back to client side. But it seems that the server can't receive any file from the client and the strange thing is if i delete the receiveFile() method in my client class, the server is able to recieve the file from client. Can somebody help me?
Server.class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class ConcurrentServer {
public static void main(String args[]) throws IOException
{
int portNumber = 20020;
ServerSocket serverSocket = new ServerSocket(portNumber);
while ( true ) {
new ServerConnection(serverSocket.accept()).start();
}
}
}
class ServerConnection extends Thread
{
Socket clientSocket;
ServerConnection (Socket clientSocket) throws SocketException
{
this.clientSocket = clientSocket;
setPriority(NORM_PRIORITY - 1);
}
public void run()
{
try{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter printOutPut = new PrintWriter(outToClient,true);
while(inFromClient.ready())
{
String request = inFromClient.readLine();
System.out.println(request);
System.out.println("test");
}
printOutPut.write("HTTP/1.1 200 OK\nConnection: close\n\n");
printOutPut.write("<b> Hello sends from Server");
printOutPut.flush();
printOutPut.close();
clientSocket.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Client.class
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SmallFileClient {
static String file="test.txt";
static PrintWriter outToServer;
static Socket socket;
public static void main(String[] args) throws IOException
{
final int PORT=20020;
String serverHostname = new String("127.0.0.1");
socket = new Socket(serverHostname, PORT);
outToServer = new PrintWriter(socket.getOutputStream(),true);
sendFile();
receiveFile();
outToServer.flush();
outToServer.close();
socket.close();
}
//read file and send file to server
public static void sendFile() throws IOException
{
BufferedReader br=new BufferedReader(new FileReader(file));
try
{
String line = br.readLine();
while(line!=null)
{
//send line to server
outToServer.write(line);
line=br.readLine();
}
}catch (Exception e){System.out.println("!!!!");}
br.close();
}
//get reply from server and print it out
public static void receiveFile() throws IOException
{
BufferedReader brComingFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
try
{
String inline = brComingFromServer.readLine();
while(inline!=null)
{
System.out.println(inline);
inline = brComingFromServer.readLine();
}
}catch (Exception e){}
}
}
Get rid of the ready() test. Change it to:
while ((line = in.readLine()) != null)
{
// ...
}
readLine() will block until data is available. At present you are stopping the read loop as soon as there isn't data available to be read without blocking. In other words you are assuming that `!ready()! means end of stream. It doesn't: see the Javadoc.

server make a txt file and client write it

I have a project that has a server which creates an empty text file.
Once my client stops writing to this file, the server should read and display the results.
My problem is that the client is connecting to the server, but whatever text the client is sending is not being written on the server side. In addition, when I exit, the server doesn't quit.
This is what I have so far:
The Server
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readUTF();
os.println(line);
os.flush();
out.write(line);
out.flush();
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
Here is my client:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null && is != null) {
try {
do{
System.out.print("Write what the client will send: ");
strout = in.nextLine();
os.writeBytes(strout);}
while(!strout.equals("exit"));
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
};
Try this.
In your server
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = br.readLine();
System.out.println(line);
os.println(line);
os.flush();
if( line != null ){
out.write(line + '\n');
out.flush();
}
}
}
And about the 'exit' part of your client try after changing
while(!strout.equals("exit"));
to
while(!strout.equalsIgnoreCase("exit"));
Hope this helps !!
Today my teacher is upload a new project because he has make a false , the project i have to make is similar which the old but the client is reading or writing a txt with number from 0-911, The client is choice randomly what is make read o write if choice read show the numbers of txt if choice write he write randomly a number from 0-911 and stop if choice the 100.
i make it but nothing show me is stack.
sever
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
int line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
boolean ch=true;
{
line =(Integer) br.read();
// System.out.println(line);
os.println(line);
os.flush();
out.write(line+"\n");
out.flush();
} while (line != 100);
os.close();
out.close();
br.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
client
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
int number=0;
Random rand = new Random(System.currentTimeMillis());
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost");
}
int choice=2;//rand.nextInt(2);
if(choice==1){
int num=is.read();
System.out.println(num);
}
else if(choice==2){
try {
do{
number=rand.nextInt(911);
// System.out.println(number);
os.writeInt(number);
}while(number!=100);
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}

Categories