- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这是我在没有任何ServerSocket
的情况下连接两个Socket
的代码:
package primary;
import java.awt.FlowLayout;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.*;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Client extends JFrame implements Runnable {
private final String myName;
private ServerSocket listener;
private Socket connection1;
private Socket connection2;
private ObjectOutputStream output1;
private ObjectOutputStream output2;
private ObjectInputStream input1;
private ObjectInputStream input2;
private Object receiveObject;
private Object1 sendObject1;
private Object2 sendObject2;
private final int[] myLocalPort;
private final int[] connectionPort;
private ExecutorService service;
private Future<Boolean> future1;
private Future<Boolean> future2;
public Client(final String myName, int[] myLocalPort, int[] connectionPort) {
super(myName);
this.myName = myName;
this.myLocalPort = myLocalPort;
this.connectionPort = connectionPort;
sendObject1 = new Object1("string1", "string2", myName);
sendObject2 = new Object2("string1", 2.5, 2, true, myName);
initComponents();
}
public void exe() {
ExecutorService eService = Executors.newCachedThreadPool();
eService.execute(this);
}
@Override
public void run() {
try {
displayMessage("Attempting connection\n");
try {
connection1 = new Socket(InetAddress.getByName("localhost"), connectionPort[0],
InetAddress.getByName("localhost"), myLocalPort[0]);
displayMessage(myName + " connection1\n");
} catch (Exception e) {
displayMessage("failed1\n");
System.err.println("1" + myName + e.getMessage() + "\n");
}
try {
connection2 = new Socket(InetAddress.getByName("localhost"), connectionPort[1],
InetAddress.getByName("localhost"), myLocalPort[1]);
displayMessage(myName + " connection2\n");
} catch (Exception e) {
displayMessage("failed2\n");
System.err.println("2" + myName + e.getMessage() + "\n");
}
displayMessage("Connected to: " + connection1.getInetAddress().getHostName() + "\n\tport: "
+ connection1.getPort() + "\n\tlocal port: " + connection1.getLocalPort() + "\n"
+ connection2.getInetAddress().getHostName() + "\n\tport: " + connection2.getPort()
+ "\n\tlocal port: " + connection2.getLocalPort() + "\n\n");
output1 = new ObjectOutputStream(connection1.getOutputStream());
output1.flush();
output2 = new ObjectOutputStream(connection2.getOutputStream());
output2.flush();
input1 = new ObjectInputStream(connection1.getInputStream());
input2 = new ObjectInputStream(connection2.getInputStream());
displayMessage("Got I/O stream\n");
setTextFieldEditable(true);
service = Executors.newFixedThreadPool(2);
future1 = service.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
processConnection(input1);
displayMessage("input1 finished");
} catch (IOException e) {
displayMessage("blah");
}
return true;
}
});
future2 = service.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
processConnection(input2);
displayMessage("input2 finished");
} catch (IOException e) {
displayMessage("foo");
}
return true;
}
});
} catch (UnknownHostException e) {
displayMessage("UnknownHostException\n");
e.printStackTrace();
} catch (EOFException e) {
displayMessage("EOFException\n");
e.printStackTrace();
} catch (IOException e) {
displayMessage("IOException\n");
e.printStackTrace();
} catch(NullPointerException e) {
System.err.println("asdf " + e.getMessage());
} finally {
try {
displayMessage("i'm here\n");
if((future1 != null && future1.get()) && (future2 != null && future2.get())) {
displayMessage(future1.get() + " " + future2.get() + "\n");
displayMessage("Closing Connection\n");
setTextFieldEditable(false);
if(!connection1.isClosed()) {
output1.close();
input1.close();
connection1.close();
}
if(!connection2.isClosed()) {
output2.close();
input2.close();
connection2.close();
}
displayMessage("connection closed\n");
}
} catch (IOException e) {
displayMessage("IOException on closing");
} catch (InterruptedException e) {
displayMessage("InterruptedException on closing");
} catch (ExecutionException e) {
displayMessage("ExecutionException on closing");
}
}
}//method run ends
private void processConnection(ObjectInputStream input) throws IOException {
String message = "";
do {
try {
receiveObject = input.readObject();
if(receiveObject instanceof String) {
message = (String) receiveObject;
displayMessage(message + "\n");
} else if (receiveObject instanceof Object1) {
Object1 receiveObject1 = (Object1) receiveObject;
displayMessage(receiveObject1.getString1() + " " + receiveObject1.getString2()
+ " " + receiveObject1.toString() + "\n");
} else if (receiveObject instanceof Object2) {
Object2 receiveObject2 = (Object2) receiveObject;
displayMessage(receiveObject2.getString1() + " " + receiveObject2.getD()
+ " " + receiveObject2.getI() + " " + receiveObject2.toString() + "\n");
}
} catch (ClassNotFoundException e) {
displayMessage("Unknown object type received.\n");
}
displayMessage(Boolean.toString(message.equals("terminate\n")));
} while(!message.equals("terminate"));
displayMessage("finished\n");
input = null;
}
private void initComponents() {
dataField = new javax.swing.JTextField();
sendButton1 = new javax.swing.JButton();
sendButton2 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
resultArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
dataField.setEditable(false);
dataField.setColumns(20);
dataField.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
dataFieldActionPerformed(evt);
}
});
sendButton1.setText("Send Object 1");
sendButton1.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButton1ActionPerformed(evt);
}
});
sendButton2.setText("Send Object 2");
sendButton2.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButton2ActionPerformed(evt);
}
});
resultArea.setColumns(25);
resultArea.setRows(15);
resultArea.setEditable(false);
resultArea.setRows(5);
jScrollPane1.setViewportView(resultArea);
add(dataField);
add(sendButton1);
add(sendButton2);
add(jScrollPane1);
pack();
}
private void dataFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sendData(evt.getActionCommand());
dataField.setText("");
}
private void sendButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sendData(sendObject1);
}
private void sendButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sendData(sendObject2);
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
resultArea.append(messageToDisplay);
}
});
}
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
dataField.setEditable(editable);
}
});
}
private void sendData(final Object object) {
try {
output1.writeObject(object);
output1.flush();
output2.writeObject(object);
output2.flush();
displayMessage(myName + ": " + object.toString() + "\n");
} catch (IOException e) {
displayMessage("Error writing object\n");
}
}
private javax.swing.JTextField dataField;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea resultArea;
private javax.swing.JButton sendButton1;
private javax.swing.JButton sendButton2;
}
主要内容:
package primary;
import javax.swing.SwingUtilities;
public class Main {
private static Object locker;
public static void main(String[] args) {
locker = new Object();
final int[][] a = new int[6][];
final int[][] b = new int[6][];
final int[][] c;
a[0] = new int[] {12340, 12341};
a[1] = new int[] {12342, 12344};
a[2] = new int[] {12342, 12343};
a[3] = new int[] {12340, 12345};
a[4] = new int[] {12344, 12345};
a[5] = new int[] {12341, 12343};
b[0] = new int[] {22340, 22341};
b[1] = new int[] {22342, 22344};
b[2] = new int[] {22342, 22343};
b[3] = new int[] {22340, 22345};
b[4] = new int[] {22344, 22345};
b[5] = new int[] {22341, 22343};
c = a;
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
Client client1 = new Client("client1", c[0], c[1]);
client1.exe();
client1.setLocation(0, 0);
client1.setVisible(true);
}
});
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
Client client2 = new Client("client2", c[2], c[3]);
client2.exe();
client2.setLocation(0, 200);
client2.setVisible(true);
}
});
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
Client client3 = new Client("client3", c[4], c[5]);
client3.exe();
client3.setLocation(0, 400);
client3.setVisible(true);
}
});
}
}
这里Object1
和Object2
只是两个可序列化对象。看起来所有的 socket 都连接得很好。如果我退出系统而不调用套接字及其输入、输出流的 close() 方法并重新运行,它仍然可以正常工作。但是,如果我在确保调用 close() 方法后退出系统,然后再次重新运行,我会得到以下结果: 1client2地址已在使用:连接
1client3Address already in use: connect
2client3Address already in use: connect
asdf null
1client1Connection refused: connect
2client2Connection refused: connect
asdf null
2client1Connection refused: connect
asdf null
我一次又一次地重新运行,我不断收到此消息,除非我等待一定时间并再次重新运行,否则它会像第一次一样正常工作。为什么会发生这样的事情呢?为什么如果我关闭套接字而不是不关闭它们会花费这么多时间?当我不关闭套接字时,它们是真的关闭还是只是连接现有连接?但是当使用 ServerSocket 时,在我关闭的情况下似乎不会发生这种情况。到底发生了什么?
另一个问题,ServerSocket
据称将其 Socket
连接末端分发到其正在监听的本地端口之外的本地端口。如果是这样,为什么当我调用 Socket.getLocalPort() 时,我会获取它接受的所有套接字的监听本地端口?
最佳答案
创建Socket
时不要使用第三个和第四个参数。没有真正需要指定本地地址,除非有 VPN,也没有真正需要指定本地端口,除了作为网络管理员想象中的虚构内容之外。
ServerSocket supposedly hands out its end of Socket connection to a localport other than on which it is listening.
不,没有。所有接受的套接字都使用相同的本地端口作为监听端口。
关于Java Socket 连接无需 ServerSocket 监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11823426/
我知道这个问题可能已经被问过,但我检查了所有这些,我认为我的情况有所不同(请友善)。所以我有两个数据集,第一个是测试数据集,第二个是我保存在数据框中的预测(预测值,这就是没有数据列的原因)。我想合并两
在 .loc 方法的帮助下,我根据同一数据框中另一列中的值来识别 Panda 数据框中某一列中的值。 下面给出了代码片段供您引用: var1 = output_df['Player'].loc[out
当我在 Windows 中使用 WinSCP 通过 Ubuntu 连接到 VMware 时,它提示: The server rejected SFTP connection, but it lis
我正在开发一个使用 xml web 服务的 android 应用程序。在 wi-fi 网络中连接时工作正常,但在 3G 网络中连接时失败(未找到 http 404)。 这不仅仅发生在设备中。为了进行测
我有一个XIB包含我的控件的文件,加载到 Interface Builder(Snow Leopard 上的 Xcode 4.0.2)中。 文件的所有者被设置为 someClassController
我在本地计算机上管理 MySQL 数据库,并通过运行以下程序通过 C 连接到它: #include #include #include int main(int argc, char** arg
我不知道为什么每次有人访问我网站上的页面时,都会打开一个与数据库的新连接。最终我到达了大约 300 并收到错误并且页面不再加载。我认为它应该工作的方式是,我将 maxIdle 设置为 30,这意味着
希望清理 NMEA GPS 中的 .txt 文件。我当前的代码如下。 deletes = ['$GPGGA', '$GPGSA', '$GPGSV', '$PSRF156', ] searchquer
我有一个 URL、一个用户名和一个密码。我想在 C# .Net WinForms 中建立 VPN 连接。 你能告诉我从哪里开始吗?任何第三方 API? 代码示例将受到高度赞赏... 最佳答案 您可以像
有没有更好的方法将字符串 vector 转换为字符 vector ,字符串之间的终止符为零。 因此,如果我有一个包含以下字符串的 vector "test","my","string",那么我想接收一
我正在编写一个库,它不断检查 android 设备的连接,并在设备连接、断开连接或互联网连接变慢时给出回调。 https://github.com/muddassir235/connection_ch
我的操作系统:Centos 7 + CLOUDLINUX 7.7当我尝试从服务器登录Mysql时 [root@server3 ~]# Mysql -u root -h localhost -P 330
我收到错误:Puma 发现此错误:无法打开到本地主机的 TCP 连接:9200(连接被拒绝 - 连接(2)用于“本地主机”端口 9200)(Faraday::ConnectionFailed)在我的
请给我一些解决以下错误的方法。 这是一个聊天应用....代码和错误如下:: conversations_controller.rb def create if Conversation.bet
我想将两个单元格中的数据连接到一个单元格中。我还想只组合那些具有相同 ID 的单元格。 任务 ID 名称 4355.2 参与者 4355.2 领袖 4462.1 在线 4462.1 快速 4597.1
我经常需要连接 TSQL 中的字段... 使用“+”运算符时 TSQL 强制您处理的两个问题是 Data Type Precedence和 NULL 值。 使用数据类型优先级,问题是转换错误。 1)
有没有在 iPad 或 iPhone 应用程序中使用 Facebook 连接。 这个想法是登录这个应用程序,然后能够看到我的哪些 facebook 用户也在使用该应用程序及其功能。 最佳答案 是的。
我在连接或打印字符串时遇到了一个奇怪的问题。我有一个 char * ,可以将其设置为字符串文字的几个值之一。 char *myStrLiteral = NULL; ... if(blah) myS
对于以下数据 - let $x := "Yahooooo !!!! Select one number - " let $y := 1 2 3 4 5 6 7 我想得到
我正在看 UDEMY for perl 的培训视频,但是视频不清晰,看起来有错误。 培训展示了如何使用以下示例连接 2 个字符串: #!usr/bin/perl print $str = "Hi";
我是一名优秀的程序员,十分优秀!