首页 > 代码库 > Java网络连接测试小例子

Java网络连接测试小例子

花了两个小时时间去看书写例子,遇到不少蛋疼的问题,把例子贴出来,以免忘记

服务器端:

import java.io.*;

import java.net.*;

public class mYServer {

         public static void main(String[] args) {

                   ServerSocket serverSocket = null;

                   Socket socket = null;

                   OutputStream os = null;

                   InputStream is = null;
                   //监听端口号
                   int port = 8898;

                   try {
                            //建立连接
                            serverSocket = new ServerSocket(port);

                            //获得连接
                            socket = serverSocket.accept();

                            //接收客户端发送内容

                            is = socket.getInputStream();

                            byte[] b = new byte[1024];

                            int n = is.read(b);

                            //输出

                            System.out.println("客户端发送内容为:" + new String(b,0,n));

                            //向客户端发送反馈内容

                            os = socket.getOutputStream();

                            os.write(b, 0, n);

                   } catch (Exception e) {

                            e.printStackTrace();

                   }finally{

                            try{

                                     //关闭流和连接

                                     os.close();

                                     is.close();

                                     socket.close();

                                     serverSocket.close();

                            }catch(Exception e){}

                   }

         }

}

客户端:

import java.io.*;
import java.net.*;

public class mYClient {

         public static void main(String[] args) {

                   Socket socket = null;

                   InputStream is = null;

                   OutputStream os = null;

                   //服务器端IP地址

                   String serverIP = "127.0.0.1";

                   //服务器端端口号

                   int port = 8898;

                   //发送内容

                   String data = http://www.mamicode.com/"成功了";>
技术分享

Java网络连接测试小例子