09 April 2016

TCPServer TCPClient

Display:
Gui a
Nhan97
Gui b
Nhan98
Gui c
Nhan99
Gui d
Nhan100
Gui e
Nhan101
Gui f
Nhan102
Gui g
Nhan103.....
package network.sample;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {
 public static void main(String args[]) {
  try {
   Socket myClient = new Socket("localhost", 9000);
   
   OutputStream os = myClient.getOutputStream();
   InputStream is = myClient.getInputStream();
   
   for(char a = 'a'; a <= 'z'; a++) {
    os.write((int) a);
    System.out.println("Gui " + a);
    
    int b = is.read();
    System.out.println("Nhan" + b);
   }
   
   myClient.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

package network.sample;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
 public static void main(String[] args) {
  ServerSocket myServer;
  try {
   myServer = new ServerSocket(9000);
   System.out.println("Server Started");
   
   Socket serverSocket = myServer.accept();
   System.out.println("Connection from " + serverSocket);
   
   OutputStream os = serverSocket.getOutputStream();
   InputStream is = serverSocket.getInputStream();

   int ch = 0;
   while (true) {
    ch = is.read();
    if (ch == -1) {
     break;
    }
    System.out.println("Nhan " + (char) ch);
    os.write(ch);
   }
   myServer.close();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang