btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
String ip = "192.168.1.25"; // 服务器端ip地址
int port = 8899;
//Socket socketSend = null;
try {
socket = new Socket(ip, port);
//connectStatus = true;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//OutputStream outputStream = null;
try {
outputStream = socket.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
outputStream.write(buff);
outputStream.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte revBuff[] = new byte[1024];
try {
inputStream.read(revBuff);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(new String(revBuff));
}
}
});
java tcp连接服务端,每隔一秒发送一条消息,双击button开启,但是这时候界面就卡死了。怎么样才能不卡死
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
空白如空 2019-09-29 19:19关注要是用多线程,你可以去网上找个tcp多线程客户端来,把你代码里面的socket改为开一个新的线程来完成
class ClientThread implements Runnable { private Socket client; public ClientThread(Socket client) { this.client = client; } @Override public void run() { try { outputStream = client.getOutputStream(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //InputStream inputStream = null; try { inputStream = client.getInputStream(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while (true) { try { outputStream.write(buff); outputStream.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } byte revBuff[] = new byte[1024]; try { inputStream.read(revBuff); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(new String(revBuff)); } } }btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { String ip = "192.168.1.25"; // 服务器端ip地址 int port = 8899; //Socket socketSend = null; try { socket = new Socket(ip, port); //connectStatus = true; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new Thread(new ClientThread(socket)).start(); } }电脑没Java 环境,没测试过,是在你代码基础上改了下
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报