[b]服务器端Server[/b][color=red][/color][size=large][/size]
[b]客户端端Client[/b][color=red][/color][size=large][/size]
[b]实现客户端Client输入字符串,服务器Server端显示输出[/b]
package com.Socket;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
/**
* @param args
*/
public static void main(String[] args) {
ServerSocket svrsoc = null;
Socket soc = null;
DataInputStream in = null;
PrintStream out = null;
InetAddress clientIP = null;
String str = null;
try {
svrsoc = new ServerSocket(8000);
System.out.println("Server start.....");
soc = svrsoc.accept();
//用于接收客户端发来的数据的输入流
in = new DataInputStream(soc.getInputStream());
//用于向客户端发送数据的输出流
out = new PrintStream(soc.getOutputStream());
clientIP = soc.getInetAddress();
System.out.println("Client IPAddress:"+clientIP);
out.println("Welcome......");
str = in.readLine();
while(!str.equals("quit")){
System.out.println("Client said:"+str);
str = in.readLine();
}
System.out.println("Client want to leave....");
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
in.close();
out.close();
soc.close();
svrsoc.close();
System.exit(0);
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
[b]客户端端Client[/b][color=red][/color][size=large][/size]
package com.Socket;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
public static void main(String[] args) {
Socket soc = null;
DataInputStream in = null;
PrintStream out = null;
DataInputStream sysin = null;
String strin = null;
String strout = null;
try {
soc = new Socket("localhost", 8000);
System.out.println("Connecting to the Server....");
//获取输入流,用于接收服务器端发送来的数据
in = new DataInputStream(soc.getInputStream());
//获取输出流,用于客户端向服务器端发送数据
out = new PrintStream(soc.getOutputStream());
strin = in.readLine();
System.out.println("Server said:" + strin);
//用户输入流
sysin = new DataInputStream(System.in);
strout = sysin.readLine();
while (!strout.equals("quit")) {
out.println(strout);
strout = sysin.readLine();
}
out.println(strout);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
} else if (out != null) {
out.close();
} else if (sysin != null) {
sysin.close();
} else if (soc != null) {
soc.close();
}
System.exit(0);
} catch (IOException e) {
}
}
}
}
[b]实现客户端Client输入字符串,服务器Server端显示输出[/b]