标签:
Java socket相对与C来说,封装性更好,所以使用上面比较简洁。服务端方面,需要一个ServerSocket对象,开启监听,利用服务端获取的链接服务端的socket对象,构建输入流和输出流,输入流是InputStream input,向上封装后是InputStreamReader inputreader,InputStreamReader对象向上封装后是BufferedReader对象。BufferedReader对象用来获取客户端发送给服务端的信息,输出流对象是OutputStream ,向上封装后是OutputStreamWriter对象,OutputStreamWriter对象向上封装后是BufferWriter对象,BufferWriter封装在PrintWriter对象中,用来向客户端发送信息。
服务端示例:
import java.io.OutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import.java.io.BufferedReader;
import java.io.BufferedWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class Server
{
public static main(String args[])
{
ServerSocket serSocket;
OutputStream outputStream;
InputStream inputStream;
BufferReader reader;
BufferReader client_reader;
PrintWriter printWriter;
Socket socket;
int PORT = 8886;
try
{
serSocket = new ServerSocket(PORT);
System.out.println("Server is running...");
socket = serSocket.accept();
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
//printWriter = new PrintWriter(outputStream,true) ------这样也可以达到封装的效果
client_reader = new BufferReader(new InputStreamReader(System.in));
while(true)
{
String message = reader.readLine();
System.out.println("client Msg: "+message);
String sendmsg = client_reader.readLine();
printWriter.println(sendmsg);
}
outputStream.close();
inputStream.close();
socket.close();
serSocket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
客户端示例:
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.Socket;
import java.net.InetAddress;
public class Client
{
public static void main(String args[])
{
Socket socket;
String host = "xxxx.xxxx.xxxx.xxxx";
int port = 8886;
BufferedReader reader;
PrintWriter printWriter;
try
{
socket = new Socket(InetAddress.getByName(host),port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
String recvmsg = reader.readLine();
String sendmsg = "HelloWorld";
printWriter.println(sendmsg);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
标签:
原文地址:http://www.cnblogs.com/q-z-c-ye/p/4433383.html