socket编程2

package tcp;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerCode 

{
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(3333); System.out.println("The Server is start: " + s); // 阻塞,直到有客户端连接 Socket socket = s.accept(); try {
System.out.println("Accept the Client: " + socket); //设置IO句柄
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); while (true)
{
String str = in.readLine();
if (str.equals("byebye")){break;}
System.out.println("In Server reveived the info: " + str);
out.println(str);
}
}
finally {
System.out.println("close the Server socket and the io.");
socket.close();
s.close();
} } }

  

package tcp;
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket;
public class ClientCode {
public static void main(String[] args) throws IOException{
Socket socket = new Socket("localhost", 3333);
try{ System.out.println("socket = " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println("Hello Server,I am "); String str = in.readLine();
System.out.println(str);
out.println("byebye");
}
finally {
System.out.println("close the Client socket and the io.");
socket.close(); }
} }

  

上一篇:iOS archive(归档)的总结


下一篇:1、Java多线程基础:进程和线程之由来