Java 不是",;“本地主机”;套接字网络示例
您可能听说过使用java套接字网络。一个简单的总结是,他正在使用Java 不是",;“本地主机”;套接字网络示例,java,sockets,Java,Sockets,您可能听说过使用java套接字网络。一个简单的总结是,他正在使用127.0.0.1IP地址在客户端和服务器之间创建连接。一切都对我有用,但当我试图更改代码并将其放在两台独立的计算机(客户端和服务器)上时,它无法建立连接。我做错了什么 服务器代码 import java.io.*; import java.net.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class Server ext
127.0.0.1
IP地址在客户端和服务器之间创建连接。一切都对我有用,但当我试图更改代码并将其放在两台独立的计算机(客户端和服务器)上时,它无法建立连接。我做错了什么
服务器代码
import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Server extends JFrame{
private JTextField userTextField;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//constructor
public Server()
{
super("My Instant Messenger");
userTextField = new JTextField();
userTextField.setEditable(false);
userTextField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{
sendMessage(event.getActionCommand());
userTextField.setText("");
}
}
);
add(userTextField, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);
}
//set up and run the server
public void startRunning(){
try{
server = new ServerSocket(6789,100);
while(true)
{
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException e){
showMessage("\n Server ended the connection! ");
}finally{
closeCrap();
}
}
}catch(IOException e){
e.printStackTrace();
}
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException{
showMessage(" Waiting for someone to connect... \n");
connection = server.accept();
showMessage(" Now Connected to " + connection.getInetAddress().getHostName());
}
//get stream to send and receive data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are now setup! \n");
}
//during the chat coversation
private void whileChatting() throws IOException{
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n " + message);
}catch(ClassNotFoundException e){
showMessage("\n idk wtf that user sent!");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets after you are done chating
private void closeCrap(){
showMessage("\n Closing connection... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException e){
e.printStackTrace();
}
}
//send a message to client
private void sendMessage (String message){
try{
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
}catch(IOException e){
chatWindow.append("\n ERROR: DUDE I CANT SEND THAT MESSAGE!");
}
}
//update chatWindow
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
//let the user type stuff into their box
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userTextField.setEditable(tof);
}
}
);
}
public static void main(String[] args){
Server sally = new Server();
sally.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sally.startRunning();
}
}
客户端代码
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame{
private JTextField userTextField;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
//constructor
public Client(String host){
super("Client");
serverIP = host;
userTextField = new JTextField();
userTextField.setEditable(false);
userTextField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userTextField.setText("");
}
}
);
add(userTextField, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
}
//connect to server
public void startRunning(){
try{
connectToServer();
setUpStreams();
whileChatting();
}catch(EOFException e){
showMessage("\n Client terminated connection");
}catch(IOException e){
e.printStackTrace();
}finally{
closeCrap();
}
}
//connect to server
private void connectToServer() throws IOException{
showMessage("Attempting connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
//set up streams to send and receive messages
private void setUpStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Dude your streams are now good to go! \n");
}
//while chating with server
private void whileChatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException e){
showMessage("\n i dont know that object type");
}
}while(!message.equals("SERVER - END"));
}
//close the streams and sockets
private void closeCrap(){
showMessage("\n closing crap down...");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException e){
e.printStackTrace();
}
}
//send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException e){
chatWindow.append("\n something messed up sending message host!");
}
}
//update chatWindow
private void showMessage(final String message){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(message);
}
}
);
}
//gives user permission to type crap into the text box
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userTextField.setEditable(tof);
}
}
);
}
public static void main (String[] args){
Client charlie;
charlie = new Client("127.0.0.1");
charlie.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
charlie.startRunning();
}
}
在IPv4和v6平台上运行时,问题在于Java本身 请尝试将serverSocket绑定到IPv4地址
“0.0.0.0”
,这意味着此主机上的所有IP都可用,或者使用客户端代码中的IP(192.168.x.x
)
像这样
server = new ServerSocket(6789, 100, InetAddress.getByName("0.0.0.0"));
我想你算出了这两台计算机的两个IP地址。你们要开哪个港口?是否有防火墙处于活动状态?(你能给我们看一下你的代码吗?)?其他网络硬件?绑定到套接字时出错?@PhilW port是6789,我也尝试了新的ServerSocket(0),但它仍然无法连接。是否有异常?您可以将代码添加到问题中吗?您需要做的事情是,在尝试运行程序之前,首先确保您可以从客户端ping服务器,然后还要确保服务器绑定的端口未被防火墙阻止。如果我使用服务器的外部IP地址,会发生什么情况?我想这就是我在不同的计算机上工作所必须做的。我试过这样做,但不起作用,我假设外部IP是您的公共WAN IP(internet)。这取决于您的网络配置:如果您有路由器/调制解调器,WAN-IP将分配给该设备,并且您的电脑有LAN IP(10.x.x.x或192.168.x.x或类似的)。您需要使用NAT(网络地址(“端口转发”)转换)来实现这一点。我将对此进行研究,但NAT(端口转发)与java中的套接字网络在哪里发生冲突?因为每次我读到其他问题和答案时,人们似乎都不会一起提到它们。这与Java无关,而是与网络有关。您必须分层查看:告诉Java打开套接字会告诉OS(操作系统)打开网络驱动程序上的套接字等。当您连接时,它会通过OS、防火墙、路由器、调制解调器等。因此,在这些步骤的任何一点上,都可能存在一个问题,这不是Java的问题,而是网络的问题(或操作系统)。由于出站连接(PC到Internet)通常正常工作,因此只剩下防火墙和路由(NAT)配置来配置入站通信