TCP Connection zu langsam

Thalion

Mitglied
Guten Tag,
ich wollte einmal Anfragen, ob jemand eine Lösung für mein Problem hätte.
Ich arbeite zur Zeit an einem kleinen Netzwerkcode, jedoch habe ich bemerkt, dass für meine Verwendungszwecke eine größere Lese-/Schreibgeschwindigkeit benötigt wird. Ich habe einige Lektüre zu NIO-Channeln, Selector und Buffern durchgearbeitet, jedoch selbst mit Verbesserung kam keine deutliche Leistungssteigerung zusammen.

Der jetzige Code schafft hochgerechnet ca. 1KB/s ( Ziel wären 5-6 MB/s ).
IDE: Eclipse Luna x64
CPU: Intel Core i7 3770K
RAM: 4x 4GB Kingston Hyperserie
Netzwerktreiber: Atheros Qualcomm Killer Network Manager ( müsste so stimmen )

Server:
Java:
import java.io.IOException;import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;




public class MainClass {
    
    private static ServerSocketChannel ssc;
    
    private static Selector selector;
    
    private static Thread[] threads = new Thread[2];


    public static void main(String[] args) throws IOException {
        init();
        selector = Selector.open();
        Thread thread;
        thread = genComThread();
        thread.start();
    }
    
    private static Thread genComThread() {
        return new Thread(new Runnable() {


            @Override
            public void run() {
                while(true) {
                    
                    try {
                        
                        SocketChannel sc;
                        if((sc = ssc.accept()) != null) {
                            sc.configureBlocking(false);
                            sc.register(selector, (SelectionKey.OP_READ | SelectionKey.OP_WRITE));
                        }
                        
                        if(selector.selectNow() > 0) {
                            processChannel(selector.selectedKeys());
                        }
                        
                        
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    
                    try {
                        Thread.sleep(0L, 1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                }
            }


            private void processChannel(Set<SelectionKey> selectedKeys) throws Exception {
                Iterator<SelectionKey> iterator = selectedKeys.iterator();
                
                SelectionKey sk;
                SocketChannel sc;
                while(iterator.hasNext()) {
                    
                    sk = iterator.next();
                    if(sk.isReadable()) {
                        sc = (SocketChannel) sk.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        
                        try {
                            System.out.print("N: " + sc.read(buffer));
                            System.out.println(" | String: " + new String(buffer.array()));
                        } catch (Exception ex) {
                            sk.cancel();
                            ex.printStackTrace();
                        }
                    }
                    
//                    iterator.remove();
                }
            }
            
        });
    }
    
    private static void init() throws IOException {
        ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress("127.0.0.1", 55555));
        ssc.configureBlocking(false);
    }


}

Client:
Java:
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Calendar;




public class CMainClass {
    
    private static SocketChannel sc;


    public static void main(String[] args) throws Exception {
        init();
        
        StringBuilder sb = new StringBuilder(Calendar.getInstance().getTime() + " | ");
        for(int i = 0; i < 1024; i ++) {
            sb.append(String.valueOf(i).substring(0, 1));
        }
        
        ByteBuffer buffer;
        buffer = ByteBuffer.allocate(sb.length());
        buffer.put(sb.toString().getBytes());
        
        buffer.flip();
        
        sc.configureBlocking(false);
        
        long t = System.nanoTime();
        while(buffer.hasRemaining()) {
            System.out.println("Write ...");
            sc.write(buffer);
        }
        System.out.println(System.nanoTime() - t + " nanos");
        
        buffer.clear();
        while(sc.read(buffer) < 1)
            Thread.sleep(0L, 1);
        System.out.println(new String(buffer.array()));
        
    }
    
    private static void init() throws Exception {
        sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("127.0.0.1", 55555));
    }


}

Vielen Dank schon im voraus.

Mit freundlichen Grüßen,
Thalion
 

Tobse

Top Contributor
1KB/s über TCP? Dann machst du was falsch. An guten Internetleitungen bekommst du mit TCP Downstreams von 8 - 10 MB/s problemlos hin. Deine Verbindung geht über localhost/127.0.0.1; da müsste noch sehr viel mehr drin sein. Du machst eindeutig was falsch :D

Such mal nach Performance-blockern. Irgendwo wartest du ggf. o.ä. Vllt ist auch einfach deine Messung mit 1KB/s falsch.
 

Thalion

Mitglied
Ok, habe das Problem gefixt bekommen.
Der ganze Fehler lag bei der größe des Buffers zum Lesen/Schreiben.
Mit kleinem Umgeschriebenem Code gehen jetzt ca. 12MB in 0.6s

Java:
import java.io.IOException;import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;




public class MainClass {
	
	private static ServerSocketChannel ssc;
	
	private static Selector selector;
	
	private static Thread[] threads = new Thread[2];


	public static void main(String[] args) throws IOException {
		init();
		selector = Selector.open();
		Thread thread;
		thread = genComThread();
		thread.start();
	}
	
	private static Thread genComThread() {
		return new Thread(new Runnable() {


			@Override
			public void run() {
				while(true) {
					
					try {
						
						SocketChannel sc;
						if((sc = ssc.accept()) != null) {
							sc.configureBlocking(false);
							sc.register(selector, (SelectionKey.OP_READ | SelectionKey.OP_WRITE));
						}
						
						if(selector.selectNow() > 0) {
							processChannel(selector.selectedKeys());
						}
						
						
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					
					try {
						Thread.sleep(0L, 1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}


			private void processChannel(Set<SelectionKey> selectedKeys) throws Exception {
				Iterator<SelectionKey> iterator = selectedKeys.iterator();
				
				SelectionKey sk;
				SocketChannel sc;
				while(iterator.hasNext()) {
					
					sk = iterator.next();
					if(sk.isReadable()) {
						sc = (SocketChannel) sk.channel();
						ByteBuffer buffer = ByteBuffer.allocate(32768);
						
						try {
							sc.read(buffer);
//							System.out.print("N: " + sc.read(buffer));
//							System.out.println(" | String: " + new String(buffer.array()));
						} catch (Exception ex) {
							sk.cancel();
							ex.printStackTrace();
						}
					}
					
//					iterator.remove();
				}
			}
			
		});
	}
	
	private static void init() throws IOException {
		ssc = ServerSocketChannel.open();
		ssc.bind(new InetSocketAddress("127.0.0.1", 55555));
		ssc.configureBlocking(false);
	}


}
Java:
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Calendar;




public class CMainClass {
	
	private static SocketChannel sc;


	public static void main(String[] args) throws Exception {
		init();
		
		ByteBuffer[] buffers = new ByteBuffer[384];
		
		StringBuilder sb = new StringBuilder(Calendar.getInstance().getTime() + " | ");
		for(int i = 0; i < 32736; i ++) {
			sb.append(String.valueOf(i).substring(0, 1));
		}
		
		for(int i = 0; i < 384; i ++) {
			ByteBuffer buffer;
			buffer = ByteBuffer.allocate(sb.length());
			buffer.put(sb.toString().getBytes());
			
			buffer.flip();
			buffers[i]  = buffer;
		}
		
		sc.configureBlocking(false);
		
		long t = System.currentTimeMillis();
		for(ByteBuffer buffer : buffers) {
			while(buffer.hasRemaining()) {
				sc.write(buffer);
			}
		}
		System.out.println(System.currentTimeMillis() - t + " millis");
		
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.clear();
		while(sc.read(buffer) < 1)
			Thread.sleep(0L, 1);
		System.out.println(new String(buffer.array()));
		
	}
	
	private static void init() throws Exception {
		sc = SocketChannel.open();
		sc.connect(new InetSocketAddress("127.0.0.1", 55555));
	}


}
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
x46 Connection reset by peer: socket write error Netzwerkprogrammierung 6
F Probleme mit Connection Reset bei Telnet Verbindung Netzwerkprogrammierung 1
S Client Server Connection Netzwerkprogrammierung 4
C Handle Connection Problem Netzwerkprogrammierung 3
R Socket InputStream readObject > Connection Reset Netzwerkprogrammierung 3
L ssh connection; Zugriff auf 'screen' Prozess Netzwerkprogrammierung 5
C Client connection per Portforwarding auf einen lokalen Serverport Netzwerkprogrammierung 3
M Connection refused? Netzwerkprogrammierung 2
D Connection refused Netzwerkprogrammierung 3
B Client/Server Connection Problem Netzwerkprogrammierung 2
D Socket Socket absichtlich so schließen, dass Gegenseite java.net.SocketException: Connection reset wirft Netzwerkprogrammierung 4
C Socket Connection refused bei Internetverbindung - Welcher Port? Netzwerkprogrammierung 5
K Socket Exception Connection reset Netzwerkprogrammierung 9
VfL_Freak Socket SocketException: Connection reset Netzwerkprogrammierung 11
C Socket Socket: Connection timed out Netzwerkprogrammierung 3
T Empfangen klappt Senden nicht - Connection timed out Netzwerkprogrammierung 12
H java.net.ConnectException: Connection refused Netzwerkprogrammierung 3
Z Socket Connection reset by peer nur per IP nicht über localhost Netzwerkprogrammierung 13
RELAXccc HTTP Connection timed out: connect ?an was kann es liegen? Netzwerkprogrammierung 4
G Exception: Connection reset by peer: socket write error Netzwerkprogrammierung 2
N Socket verliert die Connection. Netzwerkprogrammierung 4
A UCP Connection über Proxy möglich? Netzwerkprogrammierung 7
M RMI - Connection Problem Netzwerkprogrammierung 7
trash HTTP Internet Connection bei Proxy ?! Netzwerkprogrammierung 3
D Client Server Problem, Methode readline() löst SocketException "Connection reset" aus Netzwerkprogrammierung 8
H RMI Connection refused bei RMI-Registry Netzwerkprogrammierung 10
S SSH-Connection - Auto-Vervollständigung mittels TAB Netzwerkprogrammierung 4
A Chatprogramm: Connection refused Netzwerkprogrammierung 4
T RMI RMI und VPN - callbackObject Connection refused Netzwerkprogrammierung 13
A Socket Client Server Connection wird aufgebaut aber keine daten geschickt. Netzwerkprogrammierung 5
J Connection Speed Test ohne Applet Netzwerkprogrammierung 5
0din Connection refused bei localhost?! Netzwerkprogrammierung 7
M FTP-Connection über FTP-Proxy Netzwerkprogrammierung 20
T Wie connection Reset abfragen/abfangen? Netzwerkprogrammierung 10
A RMI java.rmi.ConnectException: Connection refused to host: 1 Netzwerkprogrammierung 4
M chat funktioniert nicht (Connection refused: connect) Netzwerkprogrammierung 3
G InputStreamReader lässt TCP-Connection offen Netzwerkprogrammierung 9
X URL connection Problem Netzwerkprogrammierung 3
R ConnectException: Connection refused to host: 192.168.1.4 ? Netzwerkprogrammierung 8
sparrow Connection Reset bei Webserver, Java WebStart als Client Netzwerkprogrammierung 9
tfa RMI-Problem: Connection refused to host: 127.0.0.2 Netzwerkprogrammierung 4
G Connection zu MySQL ohne ODBC Netzwerkprogrammierung 8
IT-MaD Connection reset by peer: socket write error Netzwerkprogrammierung 2
B RMI & Connection refused to host Netzwerkprogrammierung 12
G httpUnit: Connection timed out Netzwerkprogrammierung 3
lhein java.io.IOException: Unable to establish loopback connection Netzwerkprogrammierung 4
Paule Connection Applet Servlet ohne Socket bzw RMI Netzwerkprogrammierung 2
B Multithreaded Server: Connection reset Netzwerkprogrammierung 4
T JDBC Verbindungsabbruch (Connection reset) Netzwerkprogrammierung 2
M SocketException: Connection reset Netzwerkprogrammierung 10
G MAC / IP Connection Netzwerkprogrammierung 10
M Problem: connection abbrechen und login erkennen Netzwerkprogrammierung 2
M Umlaute gehen bei URL Connection verloren Netzwerkprogrammierung 6
M seltsam: java.net.SocketException: Connection reset Netzwerkprogrammierung 1
B RMI Connection Problem Netzwerkprogrammierung 13
T Dateien wia P2P Connection versenden Netzwerkprogrammierung 2
D Socketverbindung schlägt fehl - Connection refused: connect Netzwerkprogrammierung 4
H java.net.SocketException: Software caused connection abort Netzwerkprogrammierung 4
R FTP Connection zu Server Netzwerkprogrammierung 4
M Ausgangsport für FTp-Connection festlegen??? Netzwerkprogrammierung 3
P Socket Socket-Verbindung Input sehr langsam Netzwerkprogrammierung 1
V Socket UDP Server/Client Kommunikation sehr langsam Netzwerkprogrammierung 2
A UDP verlorene Pakete/ socket.receive zu langsam Netzwerkprogrammierung 27
S StringArray in .txt Datei --> langsam wegen Client/Server!? Netzwerkprogrammierung 16
J HTMLUnit arbeit sehr langsam . Alternative? Netzwerkprogrammierung 6
S TCP/IP-Kommunikation ist zu langsam Netzwerkprogrammierung 13
A Warum ist das Java "Select" so langsam? Netzwerkprogrammierung 13
C NetScanner arbeitet trotz Threads langsam Netzwerkprogrammierung 6
K RMI macht Anwendung langsam? Netzwerkprogrammierung 8
A Socketverbindungsaufbau langsam Netzwerkprogrammierung 25

Ähnliche Java Themen

Neue Themen


Oben