===== Sítě =====
Tento kód je velmi odbytý. Ale snad je na něm vidět základní práce s TCP streamy.
===== Client.java =====
package javaapplication21;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class Client extends JFrame {
PrintWriter writer;
Socket s;
public Client() throws UnknownHostException, IOException {
s = new Socket("localhost", 1234);
writer = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
setSize(200, 50);
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField text = new JTextField();
JButton send = new JButton("Send");
getContentPane().add(send, BorderLayout.EAST);
getContentPane().add(text);
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writer.println(text.getText());
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent evt) {
try {
writer.close();
s.close();
} catch (IOException ex) {
//log log
}
}
});
}
public static void main(String[] args) throws UnknownHostException, IOException {
JFrame main = new Client();
main.setVisible(true);
}
}
===== Main.java - server =====
package javaapplication21;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(1234);
System.out.println("Running server...");
while (true){
Socket client = server.accept();
System.out.println("Connection accepted");
BufferedReader r= new BufferedReader(new InputStreamReader(client.getInputStream()));
while (client.isConnected()){
String s = r.readLine();
if (s == null){
r.close();
client.close();
System.out.println("Connection closed");
break;
}else{
System.out.println("Message: "+s);
}
}
}
}
}