我正在尝试创建一个聊天应用程序(是的,我知道,不是很有创意),并且我想将套接字变量的值转换为其他方法。
但是我对应该怎么办感到困惑?
我已经尝试将其作为参数传递,由于某种原因它不起作用,还试图在方法之外声明变量,这也不起作用。
public void DeclaringVariables() throws IOException{
InetAddress group = InetAddress.getByName("239.255.255.255");
int port = 1201;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
name = sc.nextLine();
MulticastSocket socket = new MulticastSocket(port);
// Since we are deploying
socket.setTimeToLive(0);
//this on localhost only (For a subnet set it as 1)
socket.joinGroup(group);
Thread t = new Thread(new
ReadThread(socket,group,port));
// Spawn a thread for reading messages
t.start();
}
/**
*
*/
public void SendButton() {
try {
while(true) {
String message;
message = sc.nextLine();
if(message.equalsIgnoreCase(GroupChat.TERMINATE))
{
finished = true;
socket.leaveGroup(group);
socket.close();
break;
}
message = name + ": " + message;
byte[] buffer = message.getBytes();
DatagramPacket datagram = new
DatagramPacket(buffer,buffer.length,group,port);
socket.send(datagram);
}
}
catch (IOException ex) {
Logger.getLogger(ChatGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:3)
如果在多种方法中需要socket
,请考虑将其声明为类属性,而不是局部变量。这样,您可以在类构造函数中实例化它,并通过类中的所有方法对其进行访问。像这样:
public class MyClass {
// declare it here
private MulticastSocket socket;
public MyClass() {
// instantiate it here
socket = new MulticastSocket(1201);
}
public void myMethod() {
// now you can use it everywhere!
socket.someMethod();
}
}