编程实现如下内容:
1) 一台客户机从其标准输入(键盘)读取一行字符,并通过其套接字将该行发送到
服务器。
2) 服务器从其连接套接字读取一行字符。
3) 服务器将该行字符转换成大写。
4) 服务器将修改后的行通过其连接套接字再回发给客户机。
5) 客户机从其套接字中读取修改后的行,然后将该行在其标准输出(监视器)上打
印出来。
TCP实验框架:
1、实验内容有三部分构成
一、MyClientPanel.java 实现界面以及与用户的交互还有与其它两部分的交互
二、MyClient.java 实现TCP Socket读的功能
三、MyWriterClient.java 实现TCP Socket写的功能
2、三部分均实现了Runnable接口,可以直接开启单独的线程。
3、MyClient and MyWriterClient 共同继承自MyBaseClient,而MyBaseClient有静态变量,所以可以通过静态变量实现信息的交互。
代码重点解释:
1、while(true)中调用Thread.sleep(),是为了不让CPU的使用率过高
2、客户端新建Socket
socket = new Socket("127.0.0.1", 2001);
服务端新建Socket
serverSocket = new ServerSocket(2001);
socket = serverSocket.accept();
Socket 的两个得到读和写的流的方法
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//发送不成功,在这里设置了 为true之后成功了
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
3、多线程中要发送成功,需要设置上面那个true的参数
实验代码如下:
package com.example.tcp_client;
public class TCPClient {
public TCPClient() {
MyClientPanel myClientPanel = new MyClientPanel();
new Thread(myClientPanel).start();
MyClient myClient = new MyClient();
new Thread(myClient).start();
new Thread(new MyWriterClient()).start();
}
public static void main(String []args) {
new TCPClient();
}
}
package com.example.tcp_client;
import java.net.Socket;
public class MyBaseClient {
/**
* @author adam
*/
static Socket socket;
static String get_info,send_info;
}
package com.example.tcp_client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyClient extends MyBaseClient implements Runnable{
public MyClient () {
try {
socket = new Socket("127.0.0.1", 2001);
get_info = "Client init";
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
// TODO Auto-generated method stub
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getInfo();
}
}
private void getInfo() {
/*if (get_info == null) {
return;
}*/
try {
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
get_info = bufferReader.readLine();
} catch (IOException e) {
System.out.println("MyClient getinfo() Error!");
return;
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}
package com.example.tcp_client;
import java.io.IOException;
import java.io.PrintWriter;
public class MyWriterClient extends MyBaseClient implements Runnable{
/**
* @param args
*/
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendInfo();
send_info = null;
}
}
private void sendInfo() {
if (send_info == null) {
return;
}
try {
//发送不成功,在这里设置了 为true之后成功了
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(send_info);
send_info = "Client: " + send_info + "
";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.example.tcp_client;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MyClientPanel extends JFrame implements Runnable, ActionListener{
String sender,getter;
StringBuffer stringBuffer = new StringBuffer();
MyBaseClient myBaseClient = new MyBaseClient();
JPanel jp;
JTextArea jta;
JTextField jtf;
JScrollPane jsp;
JButton jb;
public MyClientPanel() {
jp = new JPanel();
jta = new JTextArea();
jtf = new JTextField();
jsp = new JScrollPane(jta);
jb = new JButton();
jtf.setCaretColor(Color.GREEN);
jtf.setForeground(Color.GREEN);
jta.setEditable(false);
jb.setText("SEND");
jb.setActionCommand("send");
jb.addActionListener(this);
jp.setLayout(new GridLayout(2,1));
jp.add(jtf);
jp.add(jb);
this.setLayout(new GridLayout(2,1));
this.add(jsp);
this.add(jp);
this.setSize(400, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Client");
}
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
if (ae.getActionCommand() == "send") {
//myBaseClient.send_info = jtf.getText();
myBaseClient.send_info = sender;
if (sender == "bye") {
System.exit(0);
}
stringBuffer.append("Client: " + sender + "
");
jta.setText(stringBuffer.toString());
jtf.setText(null);
this.repaint();
}
}
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sender = this.jtf.getText();
getter = myBaseClient.get_info;
if (myBaseClient.get_info == null) {
continue;
}
if (myBaseClient.get_info != null) {
stringBuffer.append(getter + "
");
jta.setText(stringBuffer.toString());
myBaseClient.get_info = null;
}
this.repaint();
}
}
}
UDP没有实现界面,只是实现了基本功能
UDP实现注意要点
1、UDP不同于TCP(面向连接),它是通过构建数据报文的形式来进行的。
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,9879);
public DatagramPacket(byte[] paramArrayOfByte, int paramInt1, InetAddress paramInetAddress, int paramInt2);//paramInt2是server端口号
2、服务器新建Socket,DatagramSocket serverSocket = new DatagramSocket(9879);
客户端新建Socket, DatagramSocket clientSocket=new DatagramSocket();
实验代码:
package com.example.UDPClient;
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String argv[]) throws Exception
{
BufferedReader inFromUser=new BufferedReader(
new InputStreamReader(System.in));
DatagramSocket clientSocket=new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("Agd_PC");
byte[] sendData=new byte[1024];
byte[] receiveData=new byte[1024];
String sentence=inFromUser.readLine();
sendData=sentence.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,9879);
clientSocket.send(sendPacket);
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence=new String(receivePacket.getData());
System.out.println("FROM SERVER: "+modifiedSentence.trim());
clientSocket.close();
}
}
package com.example.UDPServer;
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String argv[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9879);
byte[] sendData=new byte[1024];
byte[] receiveData=new byte[1024];
while(true) {
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String sentence=new String(receivePacket.getData());
InetAddress IPAddress=receivePacket.getAddress();
int port=receivePacket.getPort();
String capitalizedSentence=sentence.toUpperCase();
//System.out.println(port);
sendData=capitalizedSentence.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,port);
serverSocket.send(sendPacket);
}
}
}