I have a simple Java program. Program connects to the server and send the numbers. I would like to redo the program that the number was sent by pressing a button.
Button code:
/* button */
JButton b1;
b1 = new JButton("Send");
b1.addActionListener(this);
/* ActionListener */
public void actionPerformed(ActionEvent zdarzenie)
{
Object zrodlo = zdarzenie.getSource();
if (zrodlo == b1){
sendNumber(number) <------- THIS METHOD
}
}
And here I need to create method sendNumber
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
private Socket socket;
Client()
{
try {
socket = new Socket("localhost", 2020);
System.out.println("Klient dziala");
}
catch(IOException e) {
System.out.println("Uruchom serwer");
System.exit(1);
}
}
void uruchom() throws Exception
{
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()),true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
Scanner czytacz = new Scanner(System.in);
String liczba, odSerwera;
while(true) {
System.out.println("Podaj zgadywaną liczbę: ");
liczba = czytacz.nextLine();
out.println(liczba);
odSerwera = in.readLine();
System.out.println(odSerwera);
if(odSerwera.equals("Zgadłeś")) break;
}
socket.close();
}
public static void main(String args[]) throws Exception
{
Client client = new Client();
client.uruchom();
}
}
I tried this:
void sendNumber(String number)
{
out.println(number);
}
Unfortunately this is not working. Anyone know how to do this?
Try adding listener as follows: