Создание сокета с использованием IP -адресов компьютеров в той же сетиJAVA

Программисты JAVA общаются здесь
Anonymous
Создание сокета с использованием IP -адресов компьютеров в той же сети

Сообщение Anonymous »

Я пытаюсь использовать Java, чтобы сделать простое приложение для чата между двумя компьютерами в моей домашней сети Wi -Fi. При инициализации сокета мне нужно было бы поместить IP -адрес компьютера, к которому я пытаюсь подключиться. Как мне найти его, и я просто использую его прямо в качестве аргумента в конструкторе сокета?InetAddress localHost = InetAddress.getLocalHost();
String ipAddress = localHost.getHostAddress();

System.out.println("Your ip address is: " + ipAddress);
< /code>
Где -то в моем коде является подсказка для пользователя для IP -адреса компьютера, с которым они хотят общаться. Итак, у меня есть два компьютера рядом, и я вручную введет IP-адрес другого компьютера на основе того, что печатается с использованием приведенного выше кода. один и тот же компьютер (не требуется IP -адрес) с использованием разных портов. < /p>
import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class chat
{
//Main method. Argument passed when running chat is the port that the user will listen on.
public static void main(String args[])
{
int readPort = Integer.parseInt(args[0]); //Port on which reader will listen.
InetAddress bindAddress = null;

try {
// Get the local host InetAddress object
InetAddress localHost = InetAddress.getLocalHost();

// Get the IP address as a string
String ipAddress = localHost.getHostAddress();

System.out.println("Local IP Address: " + ipAddress);
bindAddress = InetAddress.getByName(ipAddress);

} catch (UnknownHostException e) {
System.err.println("Could not determine local IP address: " + e.getMessage());
}

new reader(readPort, bindAddress).start(); //Start the reader thread, passing in readPort.
new writer().start(); //Start the writer thread.
}

private static class reader extends Thread
{
/*
Creates a ServerSocket on readPort and then listens on the socket for a new connection, using the accept method.
When a new connection from the writing thread of another user arrives, it will read messages
from the connection socket that is created. It prints out all received messages.
*/
private int readPort;
private String ipAddress;
private InetAddress bindAddress;
private ServerSocket sSocket;
private Socket connection;
private ObjectInputStream in;
private String message;

public reader(int readPort, InetAddress bindAddress)
{
this.readPort = readPort;
this.bindAddress = bindAddress;
}

@Override
public void run()
{
try
{
//InetAddress bindAddress = InetAddress.getByName("127.0.0.1");
sSocket = new ServerSocket(readPort, 10, bindAddress);
//System.out.println(sSocket.getInetAddress());
connection = sSocket.accept();
in = new ObjectInputStream(connection.getInputStream());
try
{
while(true)
{
//Receive the message sent from the writing thread of the other user.
message = (String)in.readObject();
//Print the received message.
System.out.println(message);
}
}
catch(ClassNotFoundException classnot)
{
System.err.println("Data received in unknown format");
}
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
finally
{
//Close connections.
try
{
in.close();
sSocket.close();
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
}
}
}

private static class writer extends Thread
{
/*
It first reads from the keyboard for the port number that the reading thread of the other peer is listening to,
and then creates a socket connecting to that port. After the connection (socket) is successfully established,
it goes into a loop of reading a message from the keyboard and writing the message to the connection (socket).
*/
private int writePort;
private String writeIP;
private InetAddress bindAddress;
private Socket writingSocket;
private ObjectOutputStream out;
private String message;

public writer() {}

@Override
public void run()
{
try
{
//Reads in the port number for the other user from the keyboard.
Scanner scanner = new Scanner(System.in);
writePort = scanner.nextInt();
writeIP = scanner.next();
System.out.println("You want to connect to IP address: " + writeIP);
//bindAddress = InetAddress.getByName(writeIP);
//writingSocket = new Socket("localhost", writePort);
writingSocket = new Socket(writeIP, writePort);
System.out.println("Connection established");
//writingSocket = new Socket(bindAddress, writePort);
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
try
{
out = new ObjectOutputStream(writingSocket.getOutputStream());
out.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
//Reads in the message the user wants to send and then sends it.
message = bufferedReader.readLine();
sendMessage(message);
}
}
catch(IOException ioException)
{
System.out.println("Disconnect with Client ");
}
}

//Method that sends the message to the other peer.
void sendMessage(String msg)
{
try
{
out.writeObject(msg);
out.flush();
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... me-network

Вернуться в «JAVA»