优化套接字java中的性能 [英] optimize perfomance in sockets java

查看:28
本文介绍了优化套接字java中的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用套接字和线程将接收到的实时数据发送到连接到它的客户端.为此,步骤如下:

My application uses sockets and threads to send real-time data that is receiving to clients that connect to it. To do so, the steps are:

  • 连接到数据服务器,然后等待客户端
  • 启动一个线程来讨论传入的数据,对其进行格式化并将其发送给客户(如果有).
  • 当客户端连接时,它会为他打开一个线程,数据将通过该线程发送.
  • 最后,使用另一个线程来测试你正在接收和发送数据,否则它会重新连接到源.

从源接收到的数据存储在一个等待线程处理的数组中.在每个客户端线程中,接收到的数据也存储在一个数组中待发送.这样做的目的是在接收或发送数据时不会卡住.数据延迟 10 秒或更长时间到达客户

The data received from the source are stored in an array waiting to be processed by the thread. In each client thread, the received data is also stored in an array to be sent. The purpose of this is that no jams in receiving or sending data. the data is delayed 10 seconds or more to reach customers

我可以做些什么来优化性能?这是在 Windows 服务器上运行的,您能推荐任何分析器吗?

What I can do to optimize performance? This is running on a windows server, can you recommend any profiler?

非常感谢您的帮助.

数据是可变长度的字符串.一部分代码是://在类中创建源socket实现Runnable然后等待客户端

The data are strings of variable length. A part of code is: // create source socket in class implements Runnable and then waits client

Socket entrada = new Socket(servidor,Integer.parseInt(puerto));
InputStream sIn = entrada.getInputStream();  
        while (!error) {  
          try {
              s = salida.accept();
              clientes.add(new ClientThread(s));              
// run
while (((c = sIn.read()) != -1) && ((clientes.size() > 0))) {
if (c != 13 && c != 10) {
cad += (char) c;
}
if (c == 13) received[i] = cad

// In SendThread, run
// format received[i] and send result
for (i=0; i < clientes.size(); i++) {
  clientes.get(i).SendData(result);
}


// In ClientThread:
OutputString s1out = socket.getOutputStream();
// SendData
sending[i] = result;
// run
if cad forsending
              for (int j = 0;j<res.length();j++){
                try {
                    s1out.write((int)res.charAt(j));          
                  } catch (Exception e) {
                  }
              }

谢谢.

推荐答案

根据您发送的数据量,它可能是您处理流的方式.

Depending on how much data you are sending, it could be the way you are handling streams.

c = sIn.read() 一次只读取几个字节.尝试用 BufferedReader 和使用 readLine().BufferedReader 一次将读取几 kb,效率更高.readLine() 还会为您将输入分成几行,这会在一定程度上简化代码.

c = sIn.read() reads a only a few bytes at a time. Try wrapping it with a BufferedReader and using readLine(). BufferedReader will read a few kb at a time, which is much more efficient. readLine() will also break inputs into lines for you, which will simplify the code somewhat.

在客户端连接上,PrintWriter 可以帮助您一次性输出整行.

On the client connection, PrintWriter may help you to output whole lines in one go.

这篇关于优化套接字java中的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆