Socket基础编程

1、服务器端代码如下

 

package com.njupt.webservice;



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.ServerSocket;

import java.net.Socket;



public class Server {



	public static void main(String[] args) throws Exception {

		ServerSocket ss = new ServerSocket(6789);

		

		while(true){

			Socket s =  ss.accept();

			InputStream is = s.getInputStream();

			

			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			String str = br.readLine();

			

			System.out.println("客户端说:" + str);

			

			br.close();

			is.close();

			s.close();

			

		}

	}

}


 

2、客户端代码如下:

 

package com.njupt.webservice;



import java.io.BufferedWriter;

import java.io.IOException;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.net.UnknownHostException;



public class Client {



	public static void main(String[] args) throws Exception {

		Socket s = new Socket("127.0.0.1",6789);

		

		OutputStream os = s.getOutputStream();

		

		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

		

		bw.write("我喜欢章泽天?");

		

		bw.close();

		os.close();

		s.close();

	}

}


 

 

你可能感兴趣的:(socket)