Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package package1;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- *
- * @author Bob
- */
- public class Server {
- public static void main(String[] args) {
- int port = 7777;
- try {
- System.out.println("Hosting on: " + port);
- ServerSocket ss = new ServerSocket(port);
- while (true) {
- Socket s = ss.accept();
- System.out.println("Connection established, ip: "+s.getInetAddress().toString());
- Thread t = new Connection(s, port);
- t.start();
- }
- } catch (IOException e) {
- }
- }
- public static class Connection extends Thread {
- Socket s;
- int port;
- public Connection(Socket s, int port) {
- this.s = s;
- this.port = port;
- }
- @Override
- public void run() {
- try {
- PrintWriter out = new PrintWriter(s.getOutputStream(), true);
- out.println("Connected to the Server on port: " + port);
- s.close();
- } catch (IOException e) {
- System.err.println("Network error.");
- }
- }
- }
- }
- package package1;
- import java.io.IOException;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.Scanner;
- /**
- *
- * @author Bob
- */
- public class Client {
- public static void main(String[] args) {
- int port = 7777;
- Socket s = getSocket(port);
- try {
- Scanner sc = new Scanner(s.getInputStream());
- System.out.println(sc.nextLine());
- s.close();
- } catch (Exception e) {
- }
- }
- private static Socket getSocket(int port) {
- Socket s = null;
- try {
- InetAddress ip = InetAddress.getByName("localhost");
- s = new Socket(ip, port);
- } catch (UnknownHostException ex) {
- System.err.println("Unknown host.");
- } catch (IOException ex) {
- System.err.println("Network error.");
- }
- return s;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement