熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java的socket通信的demo

2022-06-13   來源: Java核心技術 

  Java代碼

  package testsocket;

  import javaioBufferedReader;

  import javaioDataInputStream;

  import javaioIOException;

  import javaioInputStreamReader;

  import javaioOutputStream;

  import javaioPrintStream;

  import ServerSocket;

  import Socket;

  import UnknownHostException;

  public class TalkMe {

  public static void main(String[] args) {

  Systemoutprintln(請輸入:IP地址);

  TalkMe talk = new TalkMe();

  talklistener()start();

  try {

  talktalker(new BufferedReader(new InputStreamReader(Systemin))readLine())start();

  } catch (IOException e) {

  eprintStackTrace();

  }

  }

  private Thread listener(){

  return new Thread() {

  public void run() {

  DataInputStream dataIS = null;

  String clientSay;

  try {

  ServerSocket server = new ServerSocket();

  Socket socket = serveraccept();

  while (true) {

  dataIS = new DataInputStream(socketgetInputStream());

  clientSay = dataISreadLine();

  Systemoutprintln(Other say: + clientSay);

  }

  } catch (IOException e) {

  eprintStackTrace();

  }

  }

  };

  }

  private Thread talker(final String ip){

  return new Thread(){

  public void run() {

  Socket socket = null;

  InputStreamReader stdin=new InputStreamReader(Systemin);

  BufferedReader br=new BufferedReader(stdin);

  DataInputStream dataIS = new DataInputStream(Systemin);

  OutputStream os;

  PrintStream ps;

  String say = ;

  boolean flag = true;

  while (flag) {

  if (flag)

  Systemoutprintln(connection );

  try {

  socket = new Socket(ip );

  Systemoutprintln(connection ok);

  flag = true;

  os = socketgetOutputStream();

  ps = new PrintStream(os);

  while (true) {

  say = dataISreadLine();

  psprintln(say);

  }

  } catch (UnknownHostException e) {

  try {

  sleep();

  } catch (InterruptedException e) {

  eprintStackTrace();

  }

  } catch (IOException e) {

  }

  }

  }

  };

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26166.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.