java服务器客户端代码,java应用服务器
java如何实现客户端向服务器端传送一个图片的代码,详细一点,最好能有注释,新手求解
public class SocketTest extends Thread {
创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于成都网站建设、网站制作、泾源网络推广、小程序设计、泾源网络营销、泾源企业策划、泾源品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联公司为所有大学生创业者提供泾源建站搭建服务,24小时服务热线:18980820575,官方网址:www.cdcxhl.com
private Socket so;
private DataInputStream in;
public static void main(String[] args) {
SocketTest app = new SocketTest();
app.startup();
}
public void startup() {
try {
// 创建服务端socket对象并指定监听端口
ServerSocket ss = new ServerSocket(9999);
System.out.println("listening...");
// 等待客户端连接
so = ss.accept();
System.out.println("connected");
// 开始读取数据
start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
// 创建socket输入流
in = new DataInputStream(so.getInputStream());
while (true) {
try {
// 定义接收缓冲区(64字节)
byte[] buf = new byte[64];
// 将数据读到接收缓冲区中,并返回实际读到的数据长度
int len = in.read(buf, 0, 64);
// 长度为-1说明到达输入流末尾,socket已关闭
if (len 1) {
System.out.println("closed");
break;
}
System.out.println("(" + len + ")");
} catch (Exception e) {
// 读数据异常
e.printStackTrace();
}
}
} catch (Exception e) {
// 监听异常
e.printStackTrace();
}
}
}
用Java完成服务器和客户端的循环聊天
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
public class ChatFrame extends JPanel{
private static final long serialVersionUID = 1L;
private int width=450,height=450;
boolean flag;
int port = 10086;
String address = "192.168.33.52";
// 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();
showTextArea.setLineWrap(true);
showTextArea.setEditable(false);
showTextArea.setForeground(new Color(0xf90033));
scrollPane1 = new JScrollPane(showTextArea);
inputTextArea = new JTextArea();
inputTextArea.setLineWrap(true);
scrollPane2 = new JScrollPane(inputTextArea);
rightPanel = new JPanel();
rightPanel.setBackground(new Color(0x0099ff));
splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,scrollPane1,scrollPane2);
splitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,splitPane1,rightPanel);
inputTextArea.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
udpSend.send(port);
inputTextArea.setText("");
break;
default:
break;
}
}
});
sendButton = new JButton("发送");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
udpSend.send(port);
inputTextArea.setText("");
}
});
closeButton = new JButton("关闭");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonpane = new JPanel();
buttonpane.add(closeButton);
buttonpane.add(sendButton);
splitPane1.setBounds(0, 0, width, height-32);
splitPane1.setDividerLocation(0.8);
splitPane2.setBounds(0, 0, width, height-32);
splitPane2.setDividerLocation(0.8);
buttonpane.setBounds(width-250, height-32, 140, 32);
this.add(splitPane2);
this.add(buttonpane);
this.setPreferredSize(new Dimension(width,height));
new Thread(new UDP_Receive(receive)).start();
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setContentPane(new ChatFrame());
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class UDP_Send{
DatagramSocket datagramSocket;
int port;
String text;
public UDP_Send(DatagramSocket datagramSocket,int port) {
this.datagramSocket = datagramSocket;
this.port = port;
}
public void send(int port) {
try {
text = new String(inputTextArea.getText().getBytes(), "utf-8");
byte buffered[] = text.getBytes();
DatagramPacket database = new DatagramPacket(buffered,
buffered.length, InetAddress.getByName(address),port) ;
showTextArea.setFont(new Font("微软雅黑", Font.CENTER_BASELINE, 24));
showTextArea.append("本机"+":\n");
showTextArea.setFont(new Font("仿宋", Font.CENTER_BASELINE, 16));
showTextArea.append(" "+text+"\n");
datagramSocket.send(database);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class UDP_Receive implements Runnable {
DatagramSocket datagramSocket;
public UDP_Receive(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
@Override
public void run() {
try {
byte buff[] = new byte[4096];
DatagramPacket database = new DatagramPacket(buff, buff.length);
while (true) {
datagramSocket.receive(database);
String text = new String(database.getData(), 0,database.getLength(),"utf-8");
showTextArea.setFont(new Font("微软雅黑", Font.CENTER_BASELINE, 24));
showTextArea.append(database.getAddress()+":\n");
showTextArea.setFont(new Font("仿宋", Font.CENTER_BASELINE, 16));
showTextArea.append(" "+text+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
JAVA聊天室 客户端 和 服务器 完整代码
CS模式的QQ这是服务器:ChatServer.javaimport java.net.*;
import java.io.*;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
app.run();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
System.out.println("服务器已经建立!");
while(numbers10)
{
Socket theSocket=theServer.accept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers++;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i=numbers-1;i++)
if(chatters[i]==c)index=i;
for(int i=index;inumbers-1;i++)
chatters[i]=chatters[i+1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i=numbers-1;i++)
line=line+chatters[i].user+":";
return line;
}
public void broadcastMessage(String line)
{
System.out.println("发布信息:"+line);
for(int i=0;i=numbers-1;i++)
chatters[i].sendMessage(line);
}
}====================================================这是客户端:ChatClient.javaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cc.createComponents();
frame.getContentPane().add(content);
frame.setSize(550,310);
frame.setVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
message.setEditable(false);
JPanel paneMsg=new JPanel();
paneMsg.setBorder(BorderFactory.createTitledBorder("聊天内容"));
paneMsg.add(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanel.setBorder(BorderFactory.createTitledBorder("在线用户:"));
listPanel.add(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnect.setEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPanel.add(new Label("服务器IP:"));
buttonPanel.add(ipField);
buttonPanel.add(new Label("端口:"));buttonPanel.add(portField);
buttonPanel.add(new Label("用户名:"));
buttonPanel.add(IDField);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
pane.add(messageField,"South");
pane.add(buttonPanel,"North");
pane.add(paneMsg,"Center");
pane.add(listPanel,"West");
connect.addActionListener(this);
disconnect.addActionListener(this);
messageField.addActionListener(this);
IDField.addActionListener(this);
ipField.addActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==connect){
user=IDField.getText();
String ip=ipField.getText();
int port =Integer.parseInt(portField.getText());
if(!user.equals("")connectToServer(ip,port,user))
{
disconnect.setEnabled(true);
connect.setEnabled(false);
}
}
if(e.getSource()==disconnect)disconnectFromServer();
if(e.getSource()==messageField)
if(theSocket!=null)
{
out.println("MESSAGE:"+messageField.getText());
messageField.setText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
out.println("LEAVE:"+user);
disconnect.setEnabled(false);
connect.setEnabled(true);
thread=null;
theSocket.close();
}catch(IOException io){}
theSocket=null;
message.setText("");
users.setText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
out.println("USER:"+user);
message.setText("");
connected=true;
thread=new Thread(this);
thread.start();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
System.out.println(line);
Message messageline;
messageline=new Message(line);
if(messageline.isValid())
{
if(messageline.getType().equals("JOIN"))
{
user=messageline.getBody();
message.append(user+"进入了聊天室\n");
}
else if(messageline.getType().equals("LIST"))
updateList(messageline.getBody());
else if(messageline.getType().equals("MESSAGE"))
message.append(messageline.getBody()+"\n");
else if(messageline.getType().equals("REMOVE"))
message.append(messageline.getBody()+"离开了聊天室\n");
}
else
message.append("出现问题:"+line+"\n");
}
public void updateList(String line)
{
users.setText("");
String str=line;
for(int i=0;i10;i++)
userList[i]="";
int index=str.indexOf(":");
int a=0;
while(index!=-1){
userList[a]=str.substring(0,index);
str=str.substring(index+1);
a++;
index=str.indexOf(":");
}
for(int i=0;i10;i++)
users.append(userList[i]+"\n");
}
public void run(){
try{
String line="";
while(connected line!=null){
line=in.readLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import java.net.*;
import java.io.*;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
this.parent=parent;
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
thePort=theSocket.getPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
out.println(line);
}
public void setupUserName(String setname){
user=setname;
//System.out.print(user+"参加");
parent.broadcastMessage("JOIN:"+user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messageline.isValid()){
if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:"+user+"说: "+messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:"+c);
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:"+line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos+1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件,先运行服务段端。。。 这是我以前学的时候写过的!希望能帮的上你
java socket,我有客户端和服务器的代码,帮我添加广播和能多人会话,加分!!代码如下
根据你的改了个!不好意思,其中读写的思路稍微有点不同!不过可以做参考!
Server端代码:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestServer {
ServerSocket s = null;
boolean started = false;//用来监听服务器是否启动!
ListServerReaderWriter clients = new ArrayListServerReaderWriter();//用来存放启动的客服端
public static void main(String[] args) {
new TestServer().start();
}
public void start() {
try {
s = new ServerSocket(5050);
started = true;
} catch(SocketException e) {
System.out.println("5050端口正在使用中!!!请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
int i = 1;
try {
while(started) {
Socket ss = s.accept();
ServerReaderWriter c = new ServerReaderWriter(ss);//建立客服端
System.out.println("第" + i + "个客服端启动!");
++i;
new Thread(c).start();//启动线程
clients.add(c);
}
} catch (EOFException e) {
System.out.println("客服端被关闭!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerReaderWriter implements Runnable { //建议使用Runnable避免你重写run方法麻烦!
private Socket s;
private DataInputStream dis = null;//注意赋值,养成好习惯!
private DataOutputStream dos = null;
private boolean bConnected = false;//用于调用连接成功后的run方法
public ServerReaderWriter(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("有客户退出!");
}
}
public void run() {
try {
while (bConnected) {
String input = dis.readUTF();
System.out.println(input);
for(int i=0; iclients.size(); ++i) {
ServerReaderWriter c = clients.get(i);
c.send(input);
}
}
} catch(SocketException e) {
System.out.println("一个客服端已关闭,请勿再像他发送信息!");
} catch (EOFException e) {
System.out.println("谢谢使用!");
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dos != null) {
dos.close();
}
if (s != null) {
s.close();
s = null;
}
//clients.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
Client端代码:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestClient extends Frame { //用到Frame生产界面比较直观
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new ClientReaderWriter());
public static void main(String[] args){
new TestClient().launchFrame();
}
public void launchFrame() {
this.setSize(300, 300); //设置客服端窗口格式
this.setLocation(400, 300);
add(tfText, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
this.pack();
this.addWindowListener(new WindowAdapter() { //监听窗口关闭事件
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 5050); //依据自己的服务器,我这里用的localhost
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("连接服务器!");
bConnected = true;
} catch(ConnectException e) {
System.out.println("请检查服务器是否启动!");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfText.getText().trim();
tfText.setText("");
try {
dos.writeUTF(str);
if(str.equals("bye")){
System.exit(0);
}
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class ClientReaderWriter implements Runnable {
public void run() {
try {
while(bConnected) {
String input = dis.readUTF();
taContent.setText(taContent.getText() + input +'\n');
}
} catch (SocketException e) {
System.out.println("轻轻的我走了!Bye-bye!");
} catch (EOFException e) {
System.out.println("我断网了,再见!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
java网络编程应该怎样在客户端和服务器间实现通信?
以前写的,照贴了。。。服务器端:import java.awt.*;\x0d\x0aimport java.awt.event.WindowAdapter;\x0d\x0aimport java.awt.event.WindowEvent;\x0d\x0aimport java.io.*;\x0d\x0aimport java.net.*;/*6、 采用UDP协议,编写一个Java网络应用程序,该应用分服务器端程序和客户端程序两部分。\x0d\x0a* 客户端指定一个服务器上的文件名,让服务器发回该文件的内容,或者提示文件不存在。\x0d\x0a* (20分)(服务端程序和客户端程序分别命名为Server.java和Client.java)*/\x0d\x0apublic class N4BT6 extends Frame\x0d\x0a{\x0d\x0aDatagramSocket socket ;\x0d\x0aDatagramPacket packet ;byte[] buf ;\x0d\x0aFile file ;\x0d\x0aFileInputStream input;\x0d\x0aString message = "该文件不存在";\x0d\x0aTextArea text;\x0d\x0apublic N4BT6(String title)\x0d\x0a{\x0d\x0asuper(title);\x0d\x0atext = new TextArea(6,4);\x0d\x0aadd(text);\x0d\x0asetSize(400, 300);\x0d\x0asetVisible(true);\x0d\x0aaddWindowListener(new WindowAdapter()\x0d\x0a{\x0d\x0apublic void windowClosing(WindowEvent e)\x0d\x0a{\x0d\x0adispose();\x0d\x0a}\x0d\x0a});\x0d\x0a\x0d\x0abuf = new byte[1024];\x0d\x0atry\x0d\x0a{\x0d\x0asocket = new DatagramSocket(1230);\x0d\x0apacket = new DatagramPacket(buf, buf.length);\x0d\x0asocket.receive(packet);\x0d\x0afile = new File(new String(packet.getData()));\x0d\x0asocket = new DatagramSocket();\x0d\x0a} \x0d\x0acatch (Exception e)\x0d\x0a{e.printStackTrace();\x0d\x0a}\x0d\x0a\x0d\x0aif(file.exists())\x0d\x0a{\x0d\x0atry\x0d\x0a{\x0d\x0abuf = new byte[(int)file.length()];\x0d\x0apacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);\x0d\x0ainput = new FileInputStream(file);\x0d\x0ainput.read(buf);\x0d\x0asocket.send(packet);\x0d\x0a}\x0d\x0acatch (IOException e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0aelse\x0d\x0a{\x0d\x0atry\x0d\x0a{\x0d\x0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,\x0d\x0aInetAddress.getLocalHost(),1234);\x0d\x0asocket.send(packet);\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a}\x0d\x0apublic static void main(String[] args)\x0d\x0a{\x0d\x0anew N4BT6("Server");\x0d\x0a}\x0d\x0a}\x0d\x0a客户端:import java.awt.*;\x0d\x0aimport java.awt.event.*;\x0d\x0aimport java.net.DatagramPacket;\x0d\x0aimport java.net.DatagramSocket;\x0d\x0aimport java.net.InetAddress;public class N4BT6_2 extends Frame\x0d\x0a{\x0d\x0aTextArea text;\x0d\x0aString message = "Q.txt";\x0d\x0aDatagramSocket socket ;\x0d\x0aDatagramPacket packet;\x0d\x0abyte[] buf;\x0d\x0apublic N4BT6_2(String title)\x0d\x0a{\x0d\x0asuper(title);\x0d\x0atext = new TextArea(6,4);\x0d\x0aadd(text);\x0d\x0asetSize(400, 300);\x0d\x0asetVisible(true);\x0d\x0aaddWindowListener(new WindowAdapter()\x0d\x0a{\x0d\x0apublic void windowClosing(WindowEvent e)\x0d\x0a{\x0d\x0adispose();\x0d\x0a}\x0d\x0a});\x0d\x0atry\x0d\x0a{\x0d\x0a\x0d\x0asocket = new DatagramSocket();\x0d\x0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,\x0d\x0aInetAddress.getLocalHost(),1230);\x0d\x0asocket.send(packet);\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a\x0d\x0atry\x0d\x0a{\x0d\x0abuf = new byte[1024];\x0d\x0asocket = new DatagramSocket(1234);\x0d\x0apacket = new DatagramPacket(buf,buf.length);\x0d\x0asocket.receive(packet);\x0d\x0atext.append(new String(buf));\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0apublic static void main(String[] args)\x0d\x0a{\x0d\x0anew N4BT6_2("Client");\x0d\x0a}\x0d\x0a}
急求一段JAVA代码,有关客户端和服务器的。。。
客户端
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
*
* @author Administrator
*/
public class Main extends JFrame{
JPanel jp;
JButton jb;
javax.swing.JTextField jt1;
JTextField jt2;
JTextField jt3;
JLabel jl1;
JLabel jl2;
public Main()
{
this.setBounds(150, 50, 300, 100);
jp= new JPanel(new GridLayout(3, 2));
jb=new JButton("登陆");
jt1=new JTextField();
jt2=new JTextField();
jt3=new JTextField();
jt3.setEditable(false);
jl1=new JLabel("用户名");
jl2=new JLabel("密码");
this.getContentPane().add(jp);
jp.add(jl1);
jp.add(jt1);
jp.add(jl2);
jp.add(jt2);
jp.add(jt3);
jp.add(jb);
this.setVisible(true);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String sentence;
String modifiedSentence = null;
//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 6789);
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("connection ok");
DataOutputStream outToServer = null;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader inFromServer = null;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
sentence=jt1.getText()+" "+jt2.getText();
try {
//System.out.println(sentence);
outToServer.writeBytes(sentence + '\n');
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
modifiedSentence = inFromServer.readLine();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("FROM SERVER:"+modifiedSentence);
jt3.setText(modifiedSentence);
try {
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception
{
Main m=new Main();
}
}
服务器端
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket=new ServerSocket(6789);
while(true){
Socket connectionSocket=welcomeSocket.accept();
BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());
clientSentence=inFromClient.readLine();
//capitalizedSentence=clientSentence.toUpperCase()+'\r'+'\n';
//outToClient.writeBytes(capitalizedSentence);
if(clientSentence.equalsIgnoreCase("admin 1234"))
outToClient.writeBytes("ok"+'\n');
else
outToClient.writeBytes("error"+'\n');
}
}
}
网站名称:java服务器客户端代码,java应用服务器
文章URL:http://scyanting.com/article/hcsdic.html