程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 簡單的java socket通訊

簡單的java socket通訊

編輯:關於JAVA

/**

class:SocketTest_SvrClit

author:chengyun

date:

with:to test socket---server program;

**/

import Java.Net.*;

import Java.io.*;

public class SocketTest_Server

{

public static void main(String[] args) throws UnknownHostException,IOException,ConnectException

{

ServerSocket aServerSocket=new ServerSocket(3434);

Socket aServer=null;

try

{

aServer=aServerSocket.accept();

try

{

BufferedReader input=new BufferedReader(new InputStreamReader(System.in));

BufferedReader in=new BufferedReader(new InputStreamReader(aServer.getInputStream()));

PrintWriter out=new PrintWriter(new OutputStreamWriter(aServer.getOutputStream()));

String serverstring=null;

String clIEntstring=null;

System.out.println("hello! enter the bye to exit.");

System.out.print("Server:wait clIEnt");

serverstring=input.readLine();

boolean done=false;

while(!done)

{

if(serverstring !=null)

{

out.println(serverstring);

out.flush();

}

clIEntstring=in.readLine();

if(clIEntstring !=null)

System.out.println("client:"+clIEntstring);

System.out.print("server:");

serverstring=input.readLine();

if(serverstring.equals("bye")) done=true;

}

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

finally

{

aServer.close();

}

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

finally

{

aServerSocket.close();

}

}

}

/**

class:SocketTest_SvrClit

author:chengyun

date:

with:to test socket---clIEnt program;

**/

import Java.Net.*;

import Java.io.*;

public class SocketTest_SvrClit

{

public static void main(String[] args) throws UnknownHostException,IOException,ConnectException

{

Socket aClIEnt=null;

aClIEnt=new Socket("192.168.0.8",3434); //InetAddress.getLocalHost()

try

{

BufferedReader input=new BufferedReader(new InputStreamReader(System.in));

BufferedReader in=new BufferedReader(new InputStreamReader(aClIEnt.getInputStream()));

PrintWriter out=new PrintWriter(new OutputStreamWriter(aClIEnt.getOutputStream()));

String clIEntString=null;

String serverString=null;

System.out.println("hello!enter bye to exit.");

boolean done=false;

while(!done)

{

serverString=in.readLine();

if(serverString !=null)

System.out.println("Server:"+serverString);

System.out.print("clIEnt:");

clIEntString=input.readLine();

if(clIEntString.equals("bye")) done=true;

if(clIEntString !=null)

{

out.println(clIEntString);

out.flush();

}

}

in.close();

out.close();

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

finally

{

aClIEnt.close();

}

}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved