i'm a beginner for coding at java . net
now i got a problem with input the port
plz see the code
package test;
import java.net.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPCliet {
final int buffSize = 10001;//buff size
final int TIMEOUT = 3000;
final int MAXTIRES = 1;
boolean receivedResponse = false;
DatagramSocket sock;
String request;
String response;
InetAddress servAddr;
int servPort;
UDPCliet(DatagramSocket s, String sName,int sPort) throws UnknownHostException
{
sock = s;
servAddr = InetAddress.getByName(sName);
servPort=sPort;
}
void makeRequest(){
request = "Hello ";//code
}
void sendRequest() throws IOException
{
try
{
byte[] sendBuff = new byte [buffSize];
sendBuff = request.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuff,sendBuff.length,servAddr,servPort);
sock.send(sendPacket);
}
catch (SocketException ex)
{
System.err.println("Exception in getRequest");
}
}
void getResponse() throws IOException{
try{
byte[] recvBuff = new byte[buffSize];
DatagramPacket recvPacket = new DatagramPacket (recvBuff,buffSize);
sock.receive(recvPacket);
recvBuff = recvPacket.getData();
response = new String(recvBuff,0,recvBuff.length);
sock.setSoTimeout(TIMEOUT);
{
}
}
catch (SocketException ex)
{
System.err.println("Response Exception");
}
}
void useResponse(){
System.out.println(response);//code for response
}
void close ()
{
sock.close();
}
// public static void main(String args []) throws IOException
// {
// final int servPort = 10001;//add port
// final String servName = "127.0.0.1" ; //add servername
//
// DatagramSocket sock = new DatagramSocket ();
// UDPCliet client = new UDPCliet (sock, servName,servPort);
//
//
//
// client.makeRequest();
// client.sendRequest();
// client.getResponse();
// client.useResponse();
// client.close();
//
}
As you can see if i set
int servPort = 10001;//add port
String servName = "127.0.0.1" ; //add server name
it will run ok
but if i change to this statement
servPort = input.nextInt();
servName = input.nextLine();
seems like i can't set the port value and server name by using Scanner keyboard
Forgive me if i use really bad english