我真的在网上搜索但我找不到我想要的东西。
我有2个类,分别是Clint和Server。这种联系在当地有效。
我想通过网络连接不同的PC。
示例:我的笔记本电脑将是服务器而我的朋友笔记本电脑将成为客户端。但我们不是同一个城市。所以我们必须使用互联网。
以下是代码: (Client.java中构造函数(host)的参数是127.0.0.1)
Client.java:
public class Client extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
//constructor
public Client(String host) {
super("Gulum Client");
serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
sendMessage(event.getActionCommand());
userText.setText("");
}
});
add(userText,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 eofException){
showMessage("\n Client terminated connection");
}catch(IOException ioexception){
ioexception.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());
}
//setup stream and recieve messages
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are now setup. \n");
}
//while chatting with server
private void whileChatting()throws IOException{
ableToType(true);
do{
try{
message = (String)input.readObject();
showMessage("\n " + message );
}catch(ClassNotFoundException classNotFounException){
showMessage("\n Unknown that object type!");
}
}while(!message.equals("SERVER - END"));
}
//close the streams and socets
private void closeCrap(){
showMessage("\n Closing connections... ");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\n CLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n Stopped to sending message!");
}
}
//change or update chatWindow
private void showMessage(final String m){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
chatWindow.append(m);
}
});
}
//gives user permisson to type crap into text box
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
userText.setEditable(tof);
}
});
}
}
Server.java:
public class Server extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
public Server(){
super("Gulum Instant Messenger");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
sendMessage(event.getActionCommand());
userText.setText("");
}
});
add(userText,BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);
}
//set up and run server
public void startRunning(){
try{
server = new ServerSocket(6789, 100);
while(true){
try{
//connect and have conversation
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Server ended the connection! ");
}finally{
closeCrap();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display information
private void waitForConnection()throws IOException{
showMessage(" Waiting for someone to connetc... \n");
connection = server.accept();
showMessage(" Now connected to " + connection.getInetAddress().getHostName());
}
//get stream to send and recieve 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 conversation
private void whileChatting()throws IOException{
String message = "You are now connected! ";
sendMessage(message);
ableToType(true);
do{
//have conversation
try{
message = (String) input.readObject();
showMessage("\n"+message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n idk wtf that user sent");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets after you are done
private void closeCrap(){
showMessage("\n Closing connections... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send a message to client
private void sendMessage(String message){
try{
output.writeObject(" SERVER - " + message);
output.flush();
showMessage("\n SERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n ERROR: THAT MESSAGE IS NOT SENT!!!");
}
}
//update chat window
private void showMessage( final String text){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
chatWindow.append(text);
}
});
}
//let user type stuff into their box
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
userText.setEditable(tof);
}
});
}
}
答案 0 :(得分:0)
您和您的朋友需要通过面向公众的IP访问彼此的计算机。如果您的每台计算机都在家庭路由器后面划分子网,则可能难以实现此目的。
我建议设置一个VPN。
以下是关于VPN的优秀文章:http://lifehacker.com/5940565/why-you-should-start-using-a-vpn-and-how-to-choose-the-best-one-for-your-needs