黑马程序员技术交流社区
标题:
java 使用socket网络通讯
[打印本页]
作者:
justinwww
时间:
2016-1-22 17:38
标题:
java 使用socket网络通讯
主要代码如下:clientimport java.net.*;
import java.io.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s = new Socket("localhost" , 8000) ;
OutputStream os = s.getOutputStream() ;
OutputStreamWriter osw = new OutputStreamWriter(os) ;
PrintWriter pw = new PrintWriter(osw,true) ;
pw.println("王洋") ;
InputStream is = s.getInputStream() ;
InputStreamReader isr = new InputStreamReader(is) ;
BufferedReader br = new BufferedReader(isr) ;
String mess = br.readLine() ;
System.out.println(mess) ;
}catch(Exception e){}
}
}
server:
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) {
try{
ServerSocket ss = new ServerSocket(8000) ;
System.out.println("监听前......") ;
Socket s = ss.accept() ;
InputStream is = s.getInputStream() ;
InputStreamReader isr = new InputStreamReader(is) ;
BufferedReader br = new BufferedReader(isr) ;
String name = br.readLine() ;
System.out.println(name) ;
OutputStream os = s.getOutputStream() ;
OutputStreamWriter osw = new OutputStreamWriter(os) ;
PrintWriter pw = new PrintWriter(osw , true) ;
pw.println("欢迎"+name) ;
}catch(Exception e){}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2