TCP编程
http://www.agoit.com/upload/picture/pic/39904/a1b7e8fc-2987-31c4-a6f6-59ba6132cfc3.bmp总结:
服务器程序编写:
①调用ServerSocket(int port)创建一个服务器端套接字,并绑定到指定端口上;②调用accept(),监听连接请求,如果客户端请求连接,则接受连接,返回通信套接字。③调用Socket类的getOutputStream()和getInputStream获取输出流和输入流,开始网络数据的发送和接收。④最后关闭通信套接字。
客户端程序编写:
①调用Socket()创建一个流套接字,并连接到服务器端; ②调用Socket类的getOutputStream()和getInputStream获取输出流和输入流,开始网络数据的发送和接收。 ③最后关闭通信套接字。
下面我们动手写一个使用TCP协议通信的服务器端可客户端:
服务器端:
package cn.com.xinli.test.socket;import java.net.*;import java.io.*;public class SocketServerextends Thread{privateSocket socket; SocketServer(Socket s) { this.socket=s; } public void run() { try {OutputStream os=socket.getOutputStream();/*在这里我们使用了带缓冲的输出流,因此与需要调用flush() *或者当缓冲区满了才会发送数据 * * */ BufferedOutputStream bos=new BufferedOutputStream(os); InputStream is=socket.getInputStream(); bos.write("欢迎你,我收到消息了!".getBytes()); bos.flush(); byte[] buf=new byte; int len=is.read(buf); System.out.println(new String(buf,0,len)); bos.close(); os.close(); is.close(); socket.close();} catch(Exception e) { e.printStackTrace(); } }public static void main(String[] args) {Socket socket=new Socket();SocketServersocketServer=new SocketServer(socket);socketServer.server(); }publicstatic void server(){System.out.println("服务器启动!");try { ServerSocket ss=new ServerSocket(6000);while(true){Socket socket=ss.accept();new SocketServer(socket).start();} } catch (Exception ex) { ex.printStackTrace(); }}}
客户端:
package cn.com.xinli.test.socket;import java.net.*;import java.io.*;public class SocketClient{public static void main(String[] args){ SocketClient.client(); } public static void client(){System.out.println("客户端启动!"); try { Socket s=new Socket(InetAddress.getByName(null),6000); OutputStream os=s.getOutputStream(); InputStream is=s.getInputStream(); byte[] buf=new byte; int len=is.read(buf); System.out.println(new String(buf,0,len)); os.write("我是流氓我怕谁".getBytes()); os.close();; is.close(); s.close(); } catch (Exception ex) { ex.printStackTrace(); }}}
先运行服务器端,后运行客户端,在双方完成通信以后,服务器端并没有推出,因为服务器端使用了多线程,每次来一个客户端请求都会开一个线程来处理
页:
[1]