Socket 服务器: 1先创建 ServerSocket ss = new ServerSocket(端口号)
2 接收请求 Socket s = ssaccept()
3接收消息 先读后写BufferedReader in = new BufferedReader(
new InputStreamReader(sgetInputStream(),"utf-8"));
String str = inreadLine(); PrintWriter out = new PrintWriter
( new BufferedWriter( new OutputStreamWriter(sgetOutputStream())),true);
outprintln("服务器信息");
4关闭流outclose();
inclose();
isclose();
客户端 1、通过IP地址和端口实例化Socket,请求连接服务器
2、获取Socket上的流以进行读写。
3、对流包装进BufferedReader/PrintWriters实例
4、关闭打开的流楼上的太长了吧,我写个简单的
import javanet;
import javaio;
import javautil;
/
TCP协议下单向通信的客户端程序。
@author new
/
public class TCPClientA {
public static void main(String[] args) {
Socket s=null;
try {
s=new Socket("127001",8888);
BufferedReader br=new BufferedReader(new InputStreamReader(sgetInputStream()));
String str=brreadLine();
Systemoutprintln(str);
} catch (Exception e) {
eprintStackTrace();
}finally{
if(s!=null)try{sclose();}catch(IOException e){}
}
}
}
================================
import javanet;
import javaio;
import javautil;
/
TCP协议下单向通信的服务器端程序。
@author new
/
public class TCPServerA {
public static void main(String[] args) {
ServerSocket ss=null;
Socket s=null;
PrintStream ps=null;
try {
ss=new ServerSocket(8888);
while(true){
Systemoutprintln("服务器已启动,在8888端口:");
s=ssaccept();
Systemoutprintln("得到 "+sgetInetAddress()+" 的连接请求");
ps=new PrintStream(sgetOutputStream());
psprintln(new Date());
psflush();
Systemoutprintln("已向客户端发送数据!");
}
} catch (IOException e) {
eprintStackTrace();
}finally{
if(ps!=null)psclose();
if(s!=null)try{sclose();}catch(IOException e){}
if(ss!=null)try{ssclose();}catch(IOException e){}
}
}
}这个,在客户端和服务端都要有cnlxzpturnUser的定义。
你把客户端的这个类编译好后,引入到服务端的类路径里面。
简单来说就是把User类编译,打包成jar文件,拷到服务端,添加到服务端的类路径里面去。import javaawtColor;
import javaawtDimension;
import javaawtFont;
import javaawteventActionEvent;
import javaawteventActionListener;
import javaawteventKeyEvent;
import javaawteventKeyListener;
import javaioIOException;
import javanetDatagramPacket;
import javanetDatagramSocket;
import javanetInetAddress;
import javaxswingJButton;
import javaxswingJFrame;
import javaxswingJPanel;
import javaxswingJScrollPane;
import javaxswingJSplitPane;
import javaxswingJTextArea;
public class ChatFrame extends JPanel{
private static final long serialVersionUID = 1L;
private int width=450,height=450;
boolean flag;
int port = 10086;
String address = "1921683352";
// int port = 2425;
DatagramSocket send;
DatagramSocket receive;
UDP_Send udpSend;
JTextArea showTextArea;
JTextArea inputTextArea;
JPanel rightPanel;
JScrollPane scrollPane1;
JScrollPane scrollPane2;
JSplitPane splitPane1;
JSplitPane splitPane2;
JButton sendButton;
JButton closeButton;
JPanel buttonpane;
public ChatFrame() throws Exception {
super(null, true);
send = new DatagramSocket();
receive = new DatagramSocket(port);
udpSend =new UDP_Send(send,port);
showTextArea = new JTextArea();
showTextAreasetLineWrap(true);
showTextAreasetEditable(false);
showTextAreasetForeground(new Color(0xf90033));
scrollPane1 = new JScrollPane(showTextArea);
inputTextArea = new JTextArea();
inputTextAreasetLineWrap(true);
scrollPane2 = new JScrollPane(inputTextArea);
rightPanel = new JPanel();
rightPanelsetBackground(new Color(0x0099ff));
splitPane1 = new JSplitPane(JSplitPaneVERTICAL_SPLIT,true,scrollPane1,scrollPane2);
splitPane2 = new JSplitPane(JSplitPaneHORIZONTAL_SPLIT,true,splitPane1,rightPanel);
inputTextAreaaddKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
switch (egetKeyCode()) {
case KeyEventVK_ENTER:
udpSendsend(port);
inputTextAreasetText("");
break;
default:
break;
}
}
});
sendButton = new JButton("发送");
sendButtonaddActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
udpSendsend(port);
inputTextAreasetText("");
}
});
closeButton = new JButton("关闭");
closeButtonaddActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Systemexit(0);
}
});
buttonpane = new JPanel();
buttonpaneadd(closeButton);
buttonpaneadd(sendButton);
splitPane1setBounds(0, 0, width, height-32);
splitPane1setDividerLocation(08);
splitPane2setBounds(0, 0, width, height-32);
splitPane2setDividerLocation(08);
buttonpanesetBounds(width-250, height-32, 140, 32);
thisadd(splitPane2);
thisadd(buttonpane);
thissetPreferredSize(new Dimension(width,height));
new Thread(new UDP_Receive(receive))start();
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
framesetContentPane(new ChatFrame());
framepack();
framesetResizable(false);
framesetLocationRelativeTo(null);
framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
framesetVisible(true);
}
class UDP_Send{
DatagramSocket datagramSocket;
int port;
String text;
public UDP_Send(DatagramSocket datagramSocket,int port) {
thisdatagramSocket = datagramSocket;
thisport = port;
}
public void send(int port) {
try {
text = new String(inputTextAreagetText()getBytes(), "utf-8");
byte buffered[] = textgetBytes();
DatagramPacket database = new DatagramPacket(buffered,
bufferedlength, InetAddressgetByName(address),port) ;
showTextAreasetFont(new Font("微软雅黑", FontCENTER_BASELINE, 24));
showTextAreaappend("本机"+":\n");
showTextAreasetFont(new Font("仿宋", FontCENTER_BASELINE, 16));
showTextAreaappend(" "+text+"\n");
datagramSocketsend(database);
} catch (IOException e) {
eprintStackTrace();
}
}
}
class UDP_Receive implements Runnable {
DatagramSocket datagramSocket;
public UDP_Receive(DatagramSocket datagramSocket) {
thisdatagramSocket = datagramSocket;
}
@Override
public void run() {
try {
byte buff[] = new byte[4096];
DatagramPacket database = new DatagramPacket(buff, bufflength);
while (true) {
datagramSocketreceive(database);
String text = new String(databasegetData(), 0,databasegetLength(),"utf-8");
showTextAreasetFont(new Font("微软雅黑", FontCENTER_BASELINE, 24));
showTextAreaappend(databasegetAddress()+":\n");
showTextAreasetFont(new Font("仿宋", FontCENTER_BASELINE, 16));
showTextAreaappend(" "+text+"\n");
}
} catch (IOException e) {
eprintStackTrace();
}
}
}
}两者都可以不过java的垃圾回收机制因为是自动的所以执行客户端程序的时候效率特别慢一般用于服务器端或WEB开发学java的重点就是以j2ee技术为核心的。想写客户端之类的用C语言是最佳的不过内存处理机制全部自己编写难度不是一般的高。我想你应该是想问C/S架构中的客户端和服务端
两者最常见的方式是通过Socket方式进行通信。
Socket可以理解成一个电线插座的工作过程:
服务器是电源插件, 客户端是电器
C和S通过电线和指定的插孔进行连接,连上后,S将电力源源不断发送到C, C就可以工作了。 当然C也可以反向发送信息到S。 两者可以相互通信。
在建立的过程中代码有一些不同。
在服务端采用API类是ServerSocket
在客户端采用的API是Socket类
连接建立后,双方都通过连接获取输入和输出流从而实现通信。即: InputStream is=socketgetInputStream();
isread();
连接代码:
S端:
ServerSocket server=null;
try {
server=new ServerSocket(指定的端口);
}catch(Exception e){
Systemoutprintln("不能监听:"+etoString());
}
Socket socket=null;
try {
socket=serveraccept();
InputStream is=socketgetInputStream();
//己通过建立起流,可以读取客户端发来的请求了
//同样也可以发送能过 sokcetgetOutputStream()
}
catch(IOException e){
Systemoutprintln("出错:"+etoString());
}finally{
try {
if(socket!=null){
socketclose();
serverclose();
}
}
catch(IOException e){
eprintStackTrace();
}
}
客户端:
Socket socket=null;
try {
socket=new Socket(url,端口);
//获取输出流,从而向服务端发数据
socketgetOutputStream();
//获取输入流,从而可以读服务端的数据
socketgetInputStream();
}catch(Exception e){
eprintStackTrace();
}
finally{
try {
socketclose();
}
catch(IOException e){
eprintStackTrace();
}
}用socket代码传啊。
如果使用的是servlet服务器技术,直接用重定向传个你的URL就行。
如果是C/S结构的程序。
就是使用socket传了。
原理差不多,服务器开个SocketServer监听
客户端用Socket连接。
然后拿到SocketgetInputStream(),拿到读入或写出流然后传就可以了。
类似于管道流,代码很好写。程序分Server和Client
服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接
一个负责客户端发送的信息(ClientMsgCollectThread 类),
另一个负责通过该Socket发送数据(ServerMsgSendThread )
Serverjava代码如下:
/
创建日期 2009-3-7
TODO 要更改此生成的文件的模板,请转至
窗口 - 首选项 - Java - 代码样式 - 代码模板
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
/
服务器端
@author Faue
/
public class Server extends ServerSocket {
private static final int SERVER_PORT = 10000;
/
构造方法,用于实现连接的监听
@throws IOException
/
public Server() throws IOException {
super(SERVER_PORT);
try {
while (true) {
Socket socket = superaccept();
new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socketgetPort())start();
new Thread(new ServerMsgSendThread(socket), "send"
+ socketgetPort())start();
}
} catch (IOException e) {
eprintStackTrace();
}
}
public static void main(String[] args) throws IOException {
new Server();
}
/
该类用于创建接收客户端发来的信息并显示的线程
@author Faue
@version 100
/
class ClientMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ClientMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
/
构造显示的字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ServerMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ServerMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
}
}
客户端:
实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收
/
创建日期 2009-3-7
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetSocket;
/
客户端
@author Faue
/
public class Client {
private Socket mySocket;
/
创建线程的构造方法
@param IP
@throws IOException
/
public Client(String IP) throws IOException {
try {
mySocket = new Socket(IP, 10000);
new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"
+ mySocketgetPort())start();
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocketgetPort())start();
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln("ServerIP:" + IP
+ " port:10000 can not be Connected");
}
}
public static void main(String[] args) throws IOException {
try {
new Client(args[0]);
} catch (Exception e) {
Systemoutprintln("输入的IP地址错误");
}
}
/
该类用于创建接收服务端发来的信息并显示的线程
@author Faue
@version 100
/
class ServerMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ServerMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
/
构造输入字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ClientMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ClientMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
outprintln("--- See you, bye! ---");
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
}
}
如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!
vaela
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)